【Leetcode】Largest Divisible Subset

来源:互联网 发布:金融入门书籍 知乎 编辑:程序博客网 时间:2024/05/03 04:28

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
原创粉丝点击