Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example 1:
nums: [1,2,3] Result: [1,2] (of course, [1,3] will also be ok)
Example 2:
nums: [1,2,4,8] Result: [1,2,4,8]
我们首先要给数组排序,之后从后往前遍历数组,因为大的数可以整除小的数, 反之则不可以。
dp[i]表示到 nums[i]位置最大可整除的子集合的长度
parent保存上一个能整除的数字的位置
mx表示最大子集合的长度
mx_idx表示起始数字的位置
如果nums[j]能整除nums[i], 且dp[i] < dp[j] + 1的话,更新dp[i]和parent[i],如果dp[i]大于mx了,还要更新mx和mx_id
最后循环结束后,根据parent数组来找到每一个数字,
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
Arrays.sort(nums);
int len = nums.length, mx = 0, mx_idx = 0;
int[] dp = new int[len], parent = new int[len];
for (int i = len - 1; i >= 0; i--) {
for (int j = i; j < len; j++) {
if (nums[j] % nums[i] == 0 && dp[i] < dp[j] + 1) {
dp[i] = dp[j] + 1;
parent[i] = j;
if (mx < dp[i]) {
mx = dp[i];
mx_idx = i;
}
}
}
}
for (int i = 0; i < mx; i++) {
res.add(nums[mx_idx]);
mx_idx = parent[mx_idx];
}
return res;
}