DP--------最大整除子集

给出一个由无重复的正整数组成的集合,找出其中最大的整除子集,子集中任意一对 (Si,Sj) 都要满足:Si % Sj = 0 或 Sj % Si = 0。

如果有多个目标子集,返回其中任何一个均可。

示例 1:

输入: [1,2,3]
输出: [1,2] (当然, [1,3] 也正确)
示例 2:

输入: [1,2,4,8]
输出: [1,2,4,8]

1.最先的想法是将数组排序,这样的话我们只需要用后面的数%前面的数就行了。

2.根据我的上一题—https://blog.csdn.net/cobracanary/article/details/88626448。
我得到一些启示,我维护一个整除数组,temp[k]代表以nums[k]结尾的最大整除子集的长度。

3.我们现在得到了数组中以每个元素结尾的最大整除子集的长度,我只需要找出这个数组最大整除子集的值,再向前找构成它的元素就行了。

class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        int len=nums.length,i,max=0,j,count[]=new int[len];
        if(len==0)
        	return new ArrayList<Integer>();
        Arrays.sort(nums);
        count[0]=1;
        for(i=1;i<len;i++) {
        	count[i]=1;
        	for(j=0;j<i;j++) {
        		if(nums[i]%nums[j]==0) {
        			count[i]=Math.max(count[i], count[j]+1);
        		}
        	}
        }
        for(i=0;i<len;i++)
        	if(count[i]>count[max])
        		max=i;//找到最大整除子集的下标
        List<Integer> ans=new LinkedList<Integer>();
        while(count[max]>1) {//向前找构成这个最大整除子集的元素
        	ans.add(nums[max]);
        	i=max-1;
        	while(count[i]!=count[max]-1||nums[max]%nums[i]!=0)
        		i--;
        	max=i;
        }
        ans.add(nums[max]);
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/cobracanary/article/details/88628057