【Leetcode】Largest Divisible Subset

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]
这道题的刚拿到手的时候非常头疼,第一反应肯定是DP,但是如何一直记录这一串数字呢?而且很担心会出现这种问题:

1,2,3,6,7,49,343。

就是对应的DP数组应该是【1,2,2,3,2,3,4】,但是实际上我们怎么知道6对应的上一个是。后来发现其实用另一个数组一直在track down最后一个跳过来的是哪个index就好了而且这个case无所谓,因为比如这个例子,2和3反正都和6相除为0,而且如果2的case比3好——也就是2之前的长度比3长,那就应该从2track过来。

也就是这个tracking的数组应该长成这个样子:【-1,0,0,2,0,4,5】

看来DP我还是学的不好。。。费了点劲才写出来,要努力了

public class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        		ArrayList<Integer> list = new ArrayList<Integer>();
		if(nums.length==0 || nums==null)
			return list;
		Arrays.sort(nums);
		int[] f = new int[nums.length];
		int[] pre = new int[nums.length];
		Arrays.fill(f, 1);
		Arrays.fill(pre, -1);
		int max = 0;
		for(int i=0;i<nums.length;i++){
			for(int j=0;j<i;j++){
				if(nums[i]%nums[j]==0 && f[j]+1 > f[i]){
					f[i] = f[j] + 1;
					pre[i] = j;
				}
			}
			if(f[i] > f[max])
				max = i;
		}
		for(int i=max;i!=-1;i=pre[i]){
			list.add(nums[i]);
		}
		return list;
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值