码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Largest Divisible Subset" !

时间:2016-06-27 13:57:39      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

Very nice DP problem. The key fact of a mutual-divisible subset: if a new number n, is divisible with the largest number m within a mutual-divisible set s, s U {n} is also a mutal-divisible subset.

class Solution {
public:
    vector<int> largestDivisibleSubset(vector<int>& nums) {
        vector<int> ret;
        int n = nums.size();
        if(n < 2) return nums;
        
        sort(nums.begin(), nums.end());
        
        typedef pair<int, int> Rec; // cnt - last inx
        
        // init
        vector<Rec> dp(n);
        for(int i = 0; i < n; i ++)
        {
            dp[i] = {1, -1};
        }
        
        //
        int max_cnt = 0;
        int max_inx = 0;
        for(int i = 1; i < n; i ++)
        for(int j = i - 1; j >= max(0,max_cnt - 2); j --)
        {
            if(nums[i] % nums[j] == 0)
            {
                int ncnt = dp[j].first + 1;
                if(ncnt > dp[i].first)
                {
                    dp[i].first = ncnt;
                    dp[i].second= j;
                }
            }
            
            if(dp[i].first > max_cnt)
            {
                max_cnt = dp[i].first;
                max_inx = i;
            }
        }
        
        // Recover the numbers
        while(max_inx >= 0)
        {
            ret.push_back(nums[max_inx]);
            max_inx = dp[max_inx].second;
        }
        reverse(ret.begin(), ret.end());
        return ret;
    }
};

LeetCode "Largest Divisible Subset" !

标签:

原文地址:http://www.cnblogs.com/tonix/p/5619892.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!