标签:
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