368. Largest Divisible Subset -- 找出一个数组使得数组内的数能够两两整除

Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.

If there are multiple solutions, return any subset is fine.

Example 1:

nums: [1,2,3]

Result: [1,2] (of course, [1,3] will also be ok)

Example 2:

nums: [1,2,4,8]

Result: [1,2,4,8]
class Solution {
public:
    vector<int> largestDivisibleSubset(vector<int>& nums) {
        int n = nums.size(), i, j, k = 0;
        if(n < 2)
            return nums;
        sort(nums.begin(), nums.end());
        vector<int> par(n), dp(n, 0);
        for(i = 0; i < n; i++)
            par[i] = i;
        for(i = 1; i < n; i++)
        {
            for(j = 0; j < i; j++)
            {
                if(nums[i] % nums[j])
                    continue;
                if(dp[j]+1 > dp[i])
                {
                    dp[i] = dp[j]+1;
                    par[i] = j;
                    if(dp[i] > dp[k])
                        k = i;
                }
            }
        }
        vector<int> ans;
        while(par[k] != k)
        {
            ans.push_back(nums[k]);
            k = par[k];
        }
        ans.push_back(nums[k]);
        return ans;
    }
};


原文地址:https://www.cnblogs.com/argenbarbie/p/5803731.html