leetcode:368.最大整除子集(动态规划)

本文提供了一种解决LeetCode上最大整除子集问题的有效算法。通过先对数组进行排序,然后使用动态规划的方法,维护一个数组来存储以每个元素为结尾的最大集合的元素个数。代码实现采用Java,详细解释了如何向前遍历处理每个元素,找到符合条件的最大子集。

链接:https://leetcode-cn.com/problems/largest-divisible-subset/
先把数组排个序,维护一个数组,存储以每个元素为结尾的最大集合的元素个数,处理每个元素时,向前遍历即可。
java代码:

class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        List<Integer>res = new ArrayList();
        if(nums.length==0)
            return res;
        int max = 1;    //存储目前可以生成的最大的集合的元素个数
        int index = 0;   //存储目前可以生成的最大集合 中 最大数的 下标
        Arrays.sort(nums);
        int [] lastIndex = new int [nums.length];  //存储每个元素的 “前一个元素” 的下标
        int [] maxSet = new int [nums.length];  //存储以每一个元素为结尾,可以生成的最大的集合的元素个数
        maxSet[0] = 1;
        lastIndex[0] = -1;
        for(int i = 1;i<nums.length;i++)
        {
            int tempMax = 0;
            int tempIndex = -1;
            for(int j = i-1;j>=0;j--)
            {
                if(nums[i]%nums[j]==0&&maxSet[j]>tempMax)
                {
                    tempMax  = maxSet[j];
                    tempIndex = j;
                }
            }
            lastIndex[i] = tempIndex;
            maxSet[i] = tempMax+1;
            if(tempMax+1>max)
            {
                max = tempMax+1;
                index = i;
            }
        }
        res.add(nums[index]);
        while(lastIndex[index]!=-1)
        {
            index = lastIndex[index];
            res.add(nums[index]);
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值