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]
用两个数组分别保存当前的长度和前一个满足条件的数的索引位置,然后从长度最大的位置往前输出
public class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> ans = new ArrayList<>();
if(nums==null || nums.length==0) return ans;
int[] pre = new int[nums.length];
int[] cnt = new int[nums.length];
Arrays.sort(nums);
int max = 0, index = -1;
for(int i=0; i<nums.length; i++){
cnt[i] = 1;
pre[i] = -1;
for(int j=i-1; j>=0; j--){
if(nums[i]%nums[j]==0){
if(1+cnt[j]>cnt[i]){
pre[i] = j;
cnt[i] = cnt[j] + 1;
}
}
}
if(cnt[i]>max){
max = cnt[i];
index = i;
}
}
while(index!=-1){
ans.add(nums[index]);
index = pre[index];
}
return ans;
}
}