result记录当前列表的长度,pre记录达到最长的上一个数字的索引,最后将数值一个一个添加至list1的
首端。返回list1.
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
if(nums.length==0){
return new ArrayList<Integer>();
}
if(nums.length==1){
List<Integer> array = new ArrayList<Integer>();
array.add(nums[0]);
return array;
}
Arrays.sort(nums);
int len = nums.length;
int[] result=new int[len];
int[] pre=new int[len];
result[0]=1;
pre[0]=-1;
int max=1;
int maxIndex=0;
for(int i=1;i<nums.length;i++){
result[i]=1;
pre[i]=-1;
for(int j=0;j<i;j++){
if(nums[i]%nums[j]==0&&result[i] < 1 + result[j]){//第二个判断条件很重要,不然有的例子过不去,例如1 2 4 8 9 72,
result[i]=result[j] + 1;
pre[i]=j;
if(result[i]>max){
max=result[i];
maxIndex=i;
}
}
}
}
List<Integer> array = new LinkedList<Integer>();
int index = maxIndex;
while(index!=-1){
array.add(0,nums[index]);
index=pre[index];
}
return array;
}
}