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]
class Solution { public: vector<int> largestDivisibleSubset(vector<int>& nums) { if(nums.size() == 0 || nums.size() == 1) return nums; sort(nums.begin(), nums.end(), greater<int>()); vector<int> route(nums.size(), -1); vector<int> dp(nums.size(), 0); int max_v = INT_MIN; for(int i = 0; i < nums.size() - 1; i++){ for(int j = i + 1; j < nums.size(); j++){ if(nums[i] % nums[j] == 0){ dp[j] = max(dp[j], dp[i] + 1); if(dp[j] == dp[i] + 1) route[j] = i; } } max_v = max(max_v, dp[i + 1]); } int start = -1; for(int i = 0; i < nums.size(); i++){ if(dp[i] == max_v) start = i; } vector<int> res; while(start != -1){ res.push_back(nums[start]); start = route[start]; } return res; } };