leetcode 377. Combination Sum IV (和的组合之四)

本文介绍了一种利用动态规划解决组合求和问题的方法,通过构建DP数组避免重复计算,有效提高了算法效率。文章详细解释了DP数组的初始化、边界条件处理以及递归计算过程。

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

Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.

Example:

nums = [1, 2, 3]
target = 4

The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

Note that different sequences are counted as different combinations.

Therefore the output is 7.

给出正数不重复的数组,找出能达到和为target的组合数,数字可以重复使用。

思路:
刚开始用dfs解,因为可以重复使用数字,最后TLE,需要转换DP思路
建立一个DP数组,长度是target+1,表示从0到target之间每个小的target有几种组合。dp[i]表示target=i的组合数。
选一个数字num,只需知道target-num有几种组合,而target-num的组合数保存在dp数组里就可以避免重复计算
dp[i] 是nums中所有数字的组合数之和。所以每算一个dp[i], 都要循环一次nums数组。

dp处理边界:target<0时,因为数组里全是正数,无法完成,所以返回0
target=0时,只需什么数字都不选,所以返回1
为避免0和未处理过的情况混淆,dp数组初始化为-1

而整个题target是正数,但是还是加入判断target=0的情况

    public int combinationSum4(int[] nums, int target) {
        if (target == 0) {
            return 1;
        }
        
        int[] dp = new int[target + 1];
        Arrays.fill(dp, -1);
        dp[0] = 1;
        return count(nums, target, dp);
    }
    
    public int count(int[] nums, int target, int[] dp) {
        if (target < 0) {
            return 0;
        }
        
        int sum = 0;
        if (dp[target] != -1) {
            return dp[target];
        }
        
        for (int i = 0; i < nums.length; i++) {
            sum += count(nums, target - nums[i], dp);
        }
        dp[target] = sum;
        return dp[target];
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值