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]
public List<Integer> largestDivisibleSubset(int[] nums) {
Arrays.sort(nums);
int[] dp = new int[nums.length];//集合第i个数的最大子集的长度
int[] pre = new int[nums.length];
Arrays.fill(dp, 1);
Arrays.fill(pre, -1);
List<Integer> result = new ArrayList<>();
int maxNum = 0, index = -1;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] % nums[j] == 0 && dp[i] < dp[j] + 1) {
dp[i] = dp[j] + 1;
pre[i] = j;//记录引起状态转移的元素,为了下面求结果集使用
}
}
if (dp[i] > maxNum) {
maxNum = dp[i];
index = i;
}
}
for (int i = index; i >= 0; ) {//求结果集
result.add(nums[i]);
i = pre[i];
}
return result;
}