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.
Example
Given nums = [1,2,3], return [1,2] or [1,3]
Given nums = [1,2,4,8], return [1,2,4,8]
Notice
If there are multiple solutions, return any subset is fine.
public class Solution {
/*
* @param nums: a set of distinct positive integers
* @return: the largest subset
*/
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> res = new ArrayList<>();
if(nums == null || nums.length <= 0) return res;
Arrays.sort(nums);
int[] size = new int[nums.length];
int[] pre = new int[nums.length];
for(int i = 0; i < nums.length; i++) {
size[i] = 1;
pre[i] = i;
}
int maxSize = 0, maxIndex = 0;
for(int i = 1; i < nums.length; i++) {
for(int j = 0; j < i; j++) {
if(nums[i] % nums[j] == 0) {
if(size[i] < size[j] + 1) {
size[i] = size[j] + 1;
pre[i] = j;
}
}
}
if(maxSize < size[i]) {
maxSize = size[i];
maxIndex = i;
}
}
while(pre[maxIndex] != maxIndex) {
res.add(nums[maxIndex]);
maxIndex = pre[maxIndex];
}
res.add(nums[maxIndex]);
return res;
}
}
public class Solution {
/*
* @param nums: a set of distinct positive integers
* @return: the largest subset
*/
//难点在于3 6 9 54,6 9 不能共存
public List<Integer> largestDivisibleSubset(int[] nums) {
//错误的解法
// Input [3,6,9,27,81,22,24,56,243,486,726,18,36,72]
// Output [81,18,3,243,486,6,9,27]
// Expected [486,243,81,27,9,3]
List<Integer> res = new ArrayList<>();
if(nums == null || nums.length <= 0) return res;
Arrays.sort(nums);
Map<Integer, HashSet<Integer>> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
map.put(nums[i], new HashSet<>());
map.get(nums[i]).add(nums[i]);
}
int maxLen = 0, head = 0;
for(int i = 1; i < nums.length; i++) {
for(int j = 0; j < i; j++) {
if(nums[i] % nums[j] == 0) {
for(Integer t : map.get(nums[j])) {
map.get(nums[i]).add(t);
}
if(maxLen < map.get(nums[i]).size()) {
maxLen = map.get(nums[i]).size();
head = i;
}
}
}
}
res.addAll(map.get(nums[head]));
return res;
}
}