【leetcode】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]

解题思路

用dp来解决,首先我们应该注意到如果对于a>b有a%b0,假设说b%c0,那么我们也会有a%c0。基于这个,首先我们将数组进行排序,然后开始从后往前计算,状态转移方程为:
dp[i]=max(dp[j]+1, dp[i]) for num[j]%num[i]
0

class Solution {
public:
    vector<int> largestDivisibleSubset(vector<int>& nums) {
        int l = nums.size();
        if (l==0||l==1)return nums;
        std::vector<int> dp(l, 0), parent(l, -1);
        sort(nums.begin(), nums.end());
        int begin = 0;
        int maxdp = 0;
        for (int i = l-1; i >=0; --i)
        {
            for (int j = i; j < l; ++j)
            {
                if (nums[j] % nums[i] == 0) {
                    dp[i] = max(dp[j]+1, dp[i]);
                    if(dp[i] == dp[j]+1) {
                        parent[i] = j;
                    }
                    if (maxdp < dp[i])
                    {
                        begin = i;
                        maxdp = dp[i];
                    }
                }
            }
        }
        // for (auto n : parent)
        // cout << n<<endl;
        std::vector<int> res;
        for (int i = 0; i < maxdp; ++i)
        {
            res.push_back(nums[begin]);
            begin = parent[begin];
        }
        return res;
    }
};
posted @ 2017-03-28 11:09  mrbean  阅读(144)  评论(0)    收藏  举报