LeetCode 377 Combination Sum IV (dp 完全背包类 推荐)

244 篇文章 0 订阅
177 篇文章 0 订阅

Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.

The test cases are generated so that the answer can fit in a 32-bit integer.

Example 1:

Input: nums = [1,2,3], target = 4
Output: 7
Explanation:
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.

Example 2:

Input: nums = [9], target = 3
Output: 0

Constraints:

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 1000
  • All the elements of nums are unique.
  • 1 <= target <= 1000

题目链接:https://leetcode.com/problems/combination-sum-iv/

题目大意:给一个数组,每个数可用多次,求组成目标数有多少种方式,不同排列属于不用方式

题目分析:本题和LeetCode-518类似,518是求组合的方式数,拿本题的样例:用[1,2,3]合成4有4种组合,分别为(1,1,1,1),(1,1,2),(1,3),(2,2),但本题求的是排列数,(1,3)和(3,1)属于两种。

下面分别贴出了两道题的做法,可以发现区别几乎就是把两层for循环的位置交换。

求组合:本质上就是一个完全背包问题,将可选数字放在外层的含义可以理解为合成当前目标数时只能对当前的枚举数字做决策,不选或选至少一个(由于下面的代码是一维的,看起来不是非常直观,不选的方案就是原来的dp[j]本身,因为每个数字可以选无数次,故内层循环从小到大),每次的选择都是针对第i个数字,从0到n-1选完之后可能会出现某个数字没选,或选了至少一次的情况,但这都是按照从左往右的顺序,也就是说对于[1,2,3]合成4是不可能出现选(3,1)这种情况的

// LeetCode 518,求组合个数
// coins = [1,2,3], amount = 4 答案为4
class Solution {
    public int change(int amount, int[] coins) {
        int[] dp = new int[amount + 1];
        dp[0] = 1;
        for (int i = 0; i < coins.length; i++) {
            for (int j = coins[i]; j <= amount; j++) {
                dp[j] += dp[j - coins[i]];
            }
        }
        return dp[amount];
    }
}

求排列:将目标数放在外层的含义可以理解为合成当前目标数时可以对所有枚举数字做决策,比如[1,2,3]合成4,dp[4]可由dp[1+3]或dp[2+2]或dp[3+1]推导而来

// LeetCode 337, 求排列个数
// nums = [1,2,3], target = 4, 答案为7
class Solution {

    public int combinationSum4(int[] nums, int target) {
        int n = nums.length;
        int[] dp = new int[target + 1];
        dp[0] = 1;
        for (int j = 1; j <= target; j++) {
            for (int i = 0; i < n; i++) {
                if (j - nums[i] >= 0) {
                    dp[j] += dp[j - nums[i]];
                }
            }
        }
        return dp[target];
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值