Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};
posted on 2016-06-27 13:20  Tonix  阅读(343)  评论(0)    收藏  举报