forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
32 lines (32 loc) · 929 Bytes
/
Solution.java
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
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
int[] f = new int[n], p = new int[n];
for (int i = 0; i < n; i++) {
int l = 1, pre = i;
for (int j = 0; j < i; j++) {
if (nums[i] % nums[j] == 0 && f[j] + 1 > l) {
l = f[j] + 1;
pre = j;
}
}
f[i] = l;
p[i] = pre;
}
int maxLen = 0, maxIndex = 0;
for (int i = 0; i < n; i++) {
if (f[i] > maxLen) {
maxLen = f[i];
maxIndex = i;
}
}
List<Integer> ans = new ArrayList<>();
while (ans.size() < maxLen) {
ans.add(nums[maxIndex]);
maxIndex = p[maxIndex];
}
Collections.reverse(ans);
return ans;
}
}