-
Notifications
You must be signed in to change notification settings - Fork 3
/
368.cpp
36 lines (36 loc) · 1017 Bytes
/
368.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
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size();
int res = 1;
int currIdx = -1;
vector<int> dp(n, 1);
vector<int> path(n, -1);
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] % nums[j] == 0) {
if (dp[j] + 1 > dp[i]) {
path[i] = j;
dp[i] = dp[j] + 1;
}
}
if (dp[i] > res) {
res = dp[i];
currIdx = i;
}
}
}
vector<int> ans;
if (res == 1) {
ans.push_back(nums[0]);
return ans;
}
for (int i = 0; i < res; i++) {
ans.push_back(nums[currIdx]);
currIdx = path[currIdx];
}
//reverse(ans.begin(), ans.end());
return ans;
}
};