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) {
         vector<int> res;
         if(nums.size()==0) return res;
        sort(nums.begin(),nums.end());
        vector<int>dp(nums.size(),1);
        vector<int>parent(nums.size(),-1);
        int max_idx = 0;
        int max_len = -1;
        for(int i = 0;i<nums.size();i++)
        {
            for(int j = 0;j<i;j++)
            {
                if(nums[i]%nums[j]==0)
                {
                    if(dp[j]+1>dp[i])
                    {
                        dp[i] = dp[j] + 1;
                        parent[i] = j;
                    } 
                }
            }
            if(dp[i]>max_len)
            {
                max_len = dp[i];
                max_idx = i;
            } 
        }
        int idx = max_idx;
        while(idx!=-1)
        {
            res.push_back(nums[idx]);
            idx = parent[idx];
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

 

 
posted @ 2018-02-09 03:10  jxr041100  阅读(109)  评论(0编辑  收藏  举报