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]

Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.

问题分析:题意要求找到一个最大的子集,子集中的任意两个数都可以相互整除。判断整除时最好判断大数整除小数,因此首先可以将nums进行排序。题目要求找到最大的子集,并不仅仅输出最大子集的数目,而且要输出最大子集是什么。对于最大子集数目可以用动态规划解决。数组dp[i]表示前i个数中最大整除子集长度,因此dp[i]=dp[j]+1,if nums[i]%nums[j]。同时可以用指针记录集合中的数。
代码如下:

    public List<Integer> largestDivisibleSubset(int[] nums) {
        int n=nums.length;
        List<Integer> result=new ArrayList<Integer>();
        if(n==0)
            return result;
        int[]dp=new int[n];
        int[]parent=new int[n];
        Arrays.sort(nums);
        dp[0]=1;
        parent[0]=-1;
        int max_id=0;
        for(int i=1;i<n;i++){
            dp[i]=1;
            parent[i]=-1;
            for(int j=0;j<i;j++){
                if(nums[i]%nums[j]==0&&dp[i]<dp[j]+1){
                    dp[i]=dp[j]+1;
                    parent[i]=j;
                }
            }
            if(dp[max_id]<dp[i]){
                max_id=i;
            }
        }
        while(max_id!=-1){
            result.add(0,nums[max_id]);
            max_id=parent[max_id];
        }
        return result;
    }

参考链接:http://bookshadow.com/weblog/2016/06/27/leetcode-largest-divisible-subset/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值