368. Largest Divisible Subset
题目链接:https://leetcode.com/problems...
dp记录最大的长度,加parent指针存路径。
dp方程是:dp[i] = max(dp[j]) + 1, if nums[i]%nums[j] == 0
public class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
if(nums.length == 0) return new ArrayList();
int n = nums.length;
Arrays.sort(nums);
// dp[i]: largest length of subset include i
int[] dp = new int[n];
dp[0] = 1;
// parent point
int[] parent = new int[n];
Arrays.fill(parent, -1);
for(int i = 0; i < n; i++) {
for(int j = 0; j < i; j++) {
if(nums[i] % nums[j] == 0 && dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
parent[i] = j;
}
}
}
int max = 0, point = 0;
for(int i = 0; i < n; i++) {
if(dp[i] > max) {
max = dp[i]; point = i;
}
}
List<Integer> res = new ArrayList();
while(point != -1) {
res.add(nums[point]);
point = parent[point];
}
return res;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。