/**
* similar with the Longest Increasing Subsequence (LIS)
* let l[i] to be the largest divisible subset ending at index i
* to determine l[i+1] we need to do,
* i. for every list l[j] in l[1] through l[i]
* if for every element in l[j], nums[i+1]%l[j]==0 or l[j]%nums[i+1]==0
* then add nums[i+1] to the end of l[j]
* else no need to change l[j]
* ii. if l[i+1].size < l[j].size, l[i+1].size = l[j].size
*
* time complexity O(n^3)
* however, if we sort the orginal array, then we don't need the inner for loop
*/
public class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> result = new ArrayList<Integer>();
if(nums==null||nums.length==0)
return result;
Arrays.sort(nums);
int[] t = new int[nums.length];
int[] index = new int[nums.length];
Arrays.fill(t, 1);
Arrays.fill(index, -1);
int max=0;
int maxIndex=-1;
for(int i=0; i<t.length; i++){
for(int j=i-1; j>=0; j--){
if(nums[i]%nums[j]==0 && t[j]+1>t[i]){
t[i]=t[j]+1;
index[i]=j;
}
}
if(max<t[i]){
max=t[i];
maxIndex=i;
}
}
int i=maxIndex;
while(i>=0){
result.add(nums[i]);
i=index[i];
}
return result;
}
}
Leetcode 368. Largest Divisible Subset
最新推荐文章于 2019-09-16 10:44:51 发布