368 最大整除合集

368. 最大整除子集

先排序,再DP,最后倒序遍历:

dp[i]表示nums[i]的最大子集的大小

cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
int len = nums.size();
std::sort(nums.begin() , nums.end());

//step1 : DP
vector<int> dp(len,1);
int maxSize = 1, maxVal = nums[0];
for(int i = 1; i<len ; ++i){
for(int j = 0; j < i; ++j){
if(nums[i] % nums[j] == 0){
dp[i] = max(dp[i],dp[j] + 1);
}
}
if(dp[i] > maxSize){
maxSize = dp[i];
maxVal = nums[i];
}
}

//step2 : Reverse traversal
vector<int> res;
if(maxSize == 1){
res.push_back(nums[0]);
return res;
}

for (int i = len - 1; i >= 0 && maxSize > 0; i--) {
if (dp[i] == maxSize && maxVal % nums[i] == 0) {
res.push_back(nums[i]);
maxVal = nums[i];
maxSize--;
}
}
return res;
}
};