zoukankan      html  css  js  c++  java
  • LeetCode "Largest Divisible Subset" !

    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;
        }
    };
  • 相关阅读:
    15回文相关问题
    14海量日志提取出现次数最多的IP
    13概率问题
    12胜者树和败者树

    pysnmp程序
    python 多线程 生产者消费者
    python多线程
    pysnmp使用
    PyYAML使用
  • 原文地址:https://www.cnblogs.com/tonix/p/5619892.html
Copyright © 2011-2022 走看看