368. Largest Divisible Subset

来源:互联网 发布:sfp端口是什么 编辑:程序博客网 时间:2024/06/05 15:47
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]
  • 这道题关键是先排序,然后倒序查找,这点比较核心。如果a[i] 小于集合中set所有的数,则a[i]如果能被集中中最小的数set[j]整除,则a[i]即可以添加到集合set中。
class Solution {public:    vector<int> largestDivisibleSubset(vector<int>& nums) {        int n = nums.size();        vector<int> parent(n,0);        vector<int> T(n,0);        int maxCnt = 0;        int maxIndex = 0;        sort(nums.begin(), nums.end());//*lowese to highest;        for(int i = n-1;i >= 0;--i){            for(int j = i;j <= n-1;++j){                if(nums[j]%nums[i] == 0 && T[j]+1 > T[i]){                    T[i] = T[j] + 1;                    parent[i] = j;                    if(T[i] > maxCnt){                        maxCnt = T[i];                        maxIndex = i;                    }                }            }        }        vector<int> res;        for(int i = 1;i <= maxCnt;++i){            res.push_back(nums[maxIndex]);            maxIndex = parent[maxIndex];        }        return res;    }};
原创粉丝点击