leetcode(368):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[i]表示以第i个数字结尾的最大集合长度,例如集合{1, 2, 4, 8}对应的dp数组为{1, 2, 3, 4}。对于排序后数组中任意下标位置n对应的数字nums[n],以nums[n]结尾的最大集合要靠下标n之前的数字来确定,假设m为n之前的任意下标,如果nums[n]能够被nums[m]整除,同时dp[n] < dp[m]+1,表明将nums[n]加入以nums[m]结尾的集合后最大集合长度比当前记录的大,更新dp[n]为dp[m]+1,依此方法遍历nums[n]之前所有数字即可得到以nums[n]结尾的最大集合长度。这样遍历整个数组即可得出以任意位置数字结尾的最大集合长度,同时记录下最终所求的最大集合长度。

题目要求最大集合,而我们只记录了最大集合长度,如何得到最大集合呢?记录下以每个数字结尾的最大集合需要的额外存储空间略大,其实我们只需依次记录下最大集合所走过的路径即可逐步还原出最大集合,用数组preIndex记录每个位置数字加入最大集合前它的前一数字下标,这样通过类似链表的形式将最大集合存储了下来,最终依次将他们存入结果中。

Java实现如下:

public class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        List<Integer> ls = new ArrayList<Integer>();
        if(nums.length==0 || nums==null) return ls;
        int len = nums.length;
        Arrays.sort(nums);
        int[] dp = new int[len];
        int[] preIndex = new int[len];
        int maxsize=0;
        int maxIndex=0;
        for (int i = 0; i < len; i++) {
            for (int j = i; j >= 0; j--) {
                if(nums[i]%nums[j]==0 && dp[i]<dp[j]+1){
                    dp[i] = dp[j]+1;
                    preIndex[i] = j;
                    if(maxsize<dp[i]){
                        maxsize=dp[i];
                        maxIndex=i;     
                    }
                }
            }
        }
        for (int i = 0; i < maxsize; i++) {
            ls.add(nums[maxIndex]);
            maxIndex=preIndex[maxIndex];
        }
        return ls;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值