题目:
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]
Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.
考虑一个有k个元素且符合要求的集合,向这个集合中加入一个数x(x大于这k个数),使得这k+1个元素的集合仍然满足要求。则这个数x必须是这k个数的倍数,此时x为最大元素。当再向集合中加入更大的元素y时,只要y是x的倍数,则y必然是前k个元素的倍数。
那么很容易想到,将集合中元素排序,用dp的方法求解以第i个数作为最大元素的最大集合。
class Solution {
public:
int* dp;
int* pre;
vector<int> largestDivisibleSubset(vector<int>& nums) {
vector<int> ans;
int n = nums.size();
if (!n) return ans;
sort(nums.begin(), nums.end());
dp = new int[n];
pre = new int[n];
for (int i = 0; i < n; i++) {
dp[i] = 1;
pre[i] = -1;
}
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++)
if (nums[i] % nums[j] == 0 && dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
pre[i] = j;
}
int maxind = 0;
int maxnum = dp[0];
for (int i = 0; i < n; i++)
if (dp[i] > maxnum) {
maxind = i;
maxnum = dp[i];
}
while (maxind != -1) {
ans.push_back(nums[maxind]);
maxind = pre[maxind];
}
reverse(ans.begin(), ans.end());
return ans;
}
};