原题网址:https://leetcode.com/problems/largest-divisible-subset/
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]方法:排序,动态规划。对于已有符合要求的子集s,新加入的元素a如果能够被s中的最大元素整除,那么s中的所有元素都能够整除a。
public class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
if (nums == null || nums.length == 0) return new ArrayList<>();
Arrays.sort(nums);
int[] prev = new int[nums.length];
int[] size = new int[nums.length];
int maxI = 0;
int maxSize = 1;
for(int i = 0; i < nums.length; i++) {
size[i] = 1;
for(int j = 0; j < i; j++) {
if (nums[i] % nums[j] == 0 && size[j] + 1 > size[i]) {
size[i] = size[j] + 1;
prev[i] = j;
}
}
if (size[i] > maxSize) {
maxSize = size[i];
maxI = i;
}
}
Integer[] subset = new Integer[maxSize];
for(int i = maxI, j = subset.length - 1; j >= 0; i = prev[i], j--) {
subset[j] = nums[i];
}
return Arrays.asList(subset);
}
}