这道题其实利用的就是这样一个事实,如果b|a,c|b,那么c|a,于是就可以利用动态规划算法.
当算法运行到第i个时,如果它能整除第j个,即nums[i] % nums[j] == 0,且在j处之前有N个可被j整除的,那么在第i处就有N+1个。
代码如下:
public class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
int size = nums.length;
Arrays.sort(nums);
int[] countOfRecord = new int[size];
int maxCount = 0;
int index = -1;
for(int i = 0;i<size;i++){
int cur = nums[i];
boolean finished = false;
for(int j = i-1;j>=0;j--){
if(cur % nums[j] == 0){//整除
finished = true;
countOfRecord[i] = countOfRecord[j]+1;
break;
}
}
if(!finished)
countOfRecord[i] = 1;
if(countOfRecord[i] > maxCount){
maxCount = countOfRecord[i];
index = i;
}
}
int count = 0;
List<Integer> res = new LinkedList<>();
for(int i = index;i>=0 && count < maxCount;i--){
if(nums[index] % nums[i] == 0){
res.add(nums[i]);
count++;
}
}
return res;
}
}
谢谢@NanzhuLin111的指正,之前的代码有些问题,原因在于,我没有考虑到诸如8、9、72这种情况的集合。
更新如下:
public class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
int size = nums.length;
Arrays.sort(nums);
int[] countOfRecord = new int[size];
int maxCount = 0;
int index = -1;
for(int i = 0;i<size;i++){
int cur = nums[i];
boolean finished = false;
int max = 0;
for(int j = i-1;j>=0;j--){
if(cur % nums[j] == 0){//整除
finished = true;
max = Math.max(countOfRecord[j]+1,max);
}
}
countOfRecord[i] = max;
if(!finished)
countOfRecord[i] = 1;
if(countOfRecord[i] > maxCount){
maxCount = countOfRecord[i];
index = i;
}
}
int count = 0;
List<Integer> res = new LinkedList<>();
for(int i = index;i>=0 && count < maxCount;i--){
if(nums[index] % nums[i] == 0){
res.add(nums[i]);
count++;
}
}
return res;
}
}