问题描述
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]
Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.
问题分析:题意要求找到一个最大的子集,子集中的任意两个数都可以相互整除。判断整除时最好判断大数整除小数,因此首先可以将nums进行排序。题目要求找到最大的子集,并不仅仅输出最大子集的数目,而且要输出最大子集是什么。对于最大子集数目可以用动态规划解决。数组dp[i]表示前i个数中最大整除子集长度,因此dp[i]=dp[j]+1,if nums[i]%nums[j]。同时可以用指针记录集合中的数。
代码如下:
public List<Integer> largestDivisibleSubset(int[] nums) {
int n=nums.length;
List<Integer> result=new ArrayList<Integer>();
if(n==0)
return result;
int[]dp=new int[n];
int[]parent=new int[n];
Arrays.sort(nums);
dp[0]=1;
parent[0]=-1;
int max_id=0;
for(int i=1;i<n;i++){
dp[i]=1;
parent[i]=-1;
for(int j=0;j<i;j++){
if(nums[i]%nums[j]==0&&dp[i]<dp[j]+1){
dp[i]=dp[j]+1;
parent[i]=j;
}
}
if(dp[max_id]<dp[i]){
max_id=i;
}
}
while(max_id!=-1){
result.add(0,nums[max_id]);
max_id=parent[max_id];
}
return result;
}
参考链接:http://bookshadow.com/weblog/2016/06/27/leetcode-largest-divisible-subset/