368. 最大整除子集
LeetCode每日一题 2021/4/23
class Solution{
public:
vector<int> largestDivisibleSubset(vector<int> &nums){
int len = nums.size();
if(len < 2) return nums;
sort(nums.begin(), nums.end());
vector<int> dp(len, 1);
vector<int> path(len, -1);
int maxIndex = -1, maxLen = 0;
for(int i = 0; i < len; i++){
for(int j = 0; j < i; j++){
if(nums[i] % nums[j] == 0){
if(dp[i] < dp[j] + 1){
dp[i] = dp[j] + 1;
path[i] = j;
}
}
}
if(dp[i] > maxLen){
maxLen = dp[i];
maxIndex = i;
}
}
int index = maxIndex;
vector<int> ans;
while(index != -1){
ans.push_back(nums[index]);
index = path[index];
}
return ans;
}
};
//解法2
class Solution{
public:
vector<int> largestDivisibleSubset(vector<int> &nums){
int len = nums.size();
if(len < 2) return nums;
sort(nums.begin(), nums.end());
using PII = pair<int, int>;
PII dp[n];
for(int i = 0; i < len; i++){
PII rec(1, i);
for(int j = 0; j < i; j++){
if(nums[i] % nums[j] == 0 && dp[j].first + 1 > rec.first){
rec = {dp[j].first + 1, j};
}
}
dp[i] = rec;
}
int idx = max_element(dp, dp + len) - dp;
int val = dp[idx].first;
vector<int> ans;
while(val--){
ans.push_back(nums[idx]);
idx = dp[idx].second;
}
return ans;
}
};