[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]表示以第i个元素为结尾的子集的最大长度,那么状态转移方程为:dp[i] = max(dp[j] + 1),其中j < i并且nums[i] % nums[j] == 0。由于题目要求返回该子串,所以还需要定义一个数组记录每个元素的上一个元素。在计算出所有的dp之后,我们遍历找出最大值,并从该值开始回溯,构造出所要求的子串。该算法的时间复杂度是O(n^2),空间复杂度是O(n)。

代码

class Solution {
public:
    vector<int> largestDivisibleSubset(vector<int>& nums) {
        if(nums.size() == 0) {
            return {};
        }
        vector<int> ret;
        sort(nums.begin(), nums.end());
        vector<int> dp(nums.size(), 1);
        vector<int> last_index(nums.size(), -1);
        for(int i = 1; i < nums.size(); ++i) {      // dynamic programming
            for(int j = i - 1; j >= 0; --j) {
                if(nums[i] % nums[j] == 0 && dp[j] + 1 > dp[i]) {
                    dp[i] = dp[j] + 1;
                    last_index[i] = j;
                }
            }
        }
        int max_length = 1, max_index = 0;
        for(int i = 1; i < dp.size(); ++i) {        // find the one with largest length
            if(dp[i] > max_length) {
                max_length = dp[i];
                max_index = i;
            }
        }
        while(max_index != -1) {                    // reconstruct the array
            ret.push_back(nums[max_index]);
            max_index = last_index[max_index];
        }
        reverse(ret.begin(), ret.end());
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值