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.
跟最长子序列类似。
1.先将数字排序;
2.dp[i]表示nums[i]可以整除的最多数;
3.有递推公式 dp[i]=max(dp[i],dp[j]+1) if dp[i]%dp[j]==0, j<i;
4.注意需要输出相应的数,只需要记录每个数i的前一个数j即可,最后从后往前回溯。
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
vector<int> res;
if (nums.size() == 0) return res;
if (nums.size() == 1){
res.push_back(nums[0]);
return res;
}
sort(nums.begin(), nums.end());
vector<int> dp(nums.size(),1);
vector<int> pre(nums.size(),-1);
int maxSize = 1;
int maxi = 0;
for (int i = 1; i < nums.size(); 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;
}
if (dp[i]>maxSize){
maxSize = dp[i];
maxi = i;
}
}
}
int i = maxi;
while (maxSize--){
res.push_back(nums[i]);
i = pre[i];
}
return res;
}
};