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]
动态规划:
o(n**2) 空间复杂度算法:
public class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
if(nums.length==0) return new ArrayList<Integer>();
Arrays.sort(nums);
List<Integer>[] dp=new List[nums.length];
dp[0]=new ArrayList<Integer>();
dp[0].add(nums[0]);
for(int i=1;i<nums.length;i++){
dp[i]=new ArrayList<Integer>();
List<Integer> temp=new ArrayList<Integer>();
for(int j=0;j<i;j++){
if(nums[i]%nums[j]==0&&dp[j].size()>temp.size()){
temp=dp[j];
}
}
List<Integer> one=new ArrayList<Integer>(temp);
one.add(nums[i]);
dp[i]=one;
}
int res=0;
for(int i=1;i<dp.length;i++){
if(dp[i].size()>dp[res].size()) res=i;
}
return dp[res];
}
}
o(n)空间复杂度算法:
public class Solution2 {
public List<Integer> largestDivisibleSubset(int[] nums) {
if(nums.length==0) return new ArrayList<Integer>();
Arrays.sort(nums);
int[] dp=new int[nums.length];
int[] path=new int[nums.length];
dp[0]=1;path[0]=-1;
Arrays.fill(path,-1);
int max=0,pos=0;
for(int i=0;i<nums.length;i++){
dp[i]=1;
for(int j=0;j<i;j++){
if(nums[i]%nums[j]==0&&dp[j]+1>dp[i]){
dp[i]=dp[j]+1;
path[i]=j;
}
}
if(dp[i]>max){
max=dp[i];pos=i;
}
}
int i=pos;
List<Integer> re=new LinkedList<Integer>();
while(i!=-1){
re.add(0,nums[i]);
i=path[i];
}
return re;
}
}