LeetCode 377: Combination Sum IV

本文介绍了两种解决组合求和IV问题的方法:一种是使用动态规划实现,通过填充dp数组来找出所有可能的组合数量;另一种是递归的暴力求解方法。这两种方法都旨在寻找数组中数字的所有组合,使得这些组合的和等于给定的目标值。
class Solution {
    public int combinationSum4(int[] nums, int target) {
        if (nums.length == 0) {
            return 0;
        }
        
        int[] dp = new int[target + 1];
        dp[0] = 1;;
        for (int i = 1; i < dp.length; i++) {
            for (int j = 0; j < nums.length; j++) {
                if (i - nums[j] >= 0) {
                    dp[i] += dp[i - nums[j]];
                }
            }
        }
        return dp[target];
        
    }
}

It's like the packing problem.

 

 

Brute force:

class Solution {
    public int combinationSum4(int[] nums, int target) {
        if (target < 0) {
            return 0;
        }
        if (target == 0) {
            return 1;
        }
        int result = 0;
        for(int num : nums) {
            result += combinationSum4(nums, target - num);
        }
        
        return result;
        
    }
}

 

转载于:https://www.cnblogs.com/shuashuashua/p/7452978.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值