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是不能用来求解具体方案的,但是这个题目中只是要求返回任意的一个,因此也是可以使用DP来做的。
java
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> arr = new ArrayList<>();
if (nums == null || nums.length == 0) {
return arr;
}
Arrays.sort(nums);
int[] f = new int[nums.length];
int[] rec = new int[nums.length];
for (int i = 0; i < f.length; i++) {
f[i] = 1;
rec[i] = -1;
}
for (int i = 1; i < f.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] % nums[j] == 0) {
if (f[i] > f[j] + 1) {
continue;
} else {
f[i] = f[j] + 1;
rec[i] = j;
}
}
}
}
int sum = 0;
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (sum < f[i]) {
sum = f[i];
index = i;
} else {
continue;
}
}
arr.add(nums[index]);
while (rec[index] != -1) {
arr.add(0, nums[rec[index]]);
index = rec[index];
}
return arr;
}
}