Leetcode 368. Largest Divisible Subset

本文介绍了一种算法,用于找出一个给定正整数数组中的最大子集,该子集中任意两个元素都能相互整除。通过逆序遍历排序后的数组并使用动态规划的方法,实现了高效求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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]表示到 nums[i]位置最大可整除的子集合的长度

parent保存上一个能整除的数字的位置

mx表示最大子集合的长度

mx_idx表示起始数字的位置

如果nums[j]能整除nums[i], 且dp[i] < dp[j] + 1的话,更新dp[i]和parent[i],如果dp[i]大于mx了,还要更新mx和mx_id

最后循环结束后,根据parent数组来找到每一个数字,

public List<Integer> largestDivisibleSubset(int[] nums) {
        List<Integer> res = new ArrayList<>();
        if (nums == null || nums.length == 0) return res;
        Arrays.sort(nums);
        
        int len = nums.length, mx = 0, mx_idx = 0;
        int[] dp = new int[len], parent = new int[len];
        for (int i = len - 1; i >= 0; i--) {
            for (int j = i; j < len; j++) {
                if (nums[j] % nums[i] == 0 && dp[i] < dp[j] + 1) {
                    dp[i] = dp[j] + 1;
                    parent[i] = j;
                    if (mx < dp[i]) {
                        mx = dp[i];
                        mx_idx = i;
                    }
                }
            }
        }
        for (int i = 0; i < mx; i++) {
            res.add(nums[mx_idx]);
            mx_idx = parent[mx_idx];
        }
        return res;
    }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值