LC.P368[最大整除子集]

方法一:动态规划

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
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
int[] f = new int[n], g = new int[n];
for (int i = 0; i < n; ++i) {
int len = 1, prev = i;
for (int j = 0; j < i; ++j) {
if (nums[i] % nums[j] == 0) {
if (f[j] + 1 > len) {
len = f[j] + 1;
prev = j;
}
}
}
f[i] = len;
g[i] = prev;
}
int max = -1, idx = -1;
for (int i = 0; i < n; ++i) {
if (f[i] > max) {
idx = i;
max = f[i];
}
}
List<Integer> ans = new ArrayList<>();
while (ans.size() < max) {
ans.add(nums[idx]);
idx = g[idx];
}
return ans;
}
}
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(n)$