第九章 动态规划part06

64 阅读1分钟

518. Coin Change II

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.

You may assume that you have an infinite number of each kind of coin.

The answer is guaranteed to fit into a signed 32-bit integer.

题目解析:

  • 每种物品有无限件,是完全背包,遍历背包方式从小到大,而01背包是从大到小遍历背包

代码:

class Solution {
    public int change(int amount, int[] coins) {
        int[] dp = new int[amount + 1];
        dp[0] = 1;
        for(int coin : coins) {
            for (int i=coin; i <= amount; i++) {
                dp[i] += dp[i-coin];
            }
        }
        return dp[amount];
    }
}

377. Combination Sum IV

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.

题目解析:

  • 因为不同的顺序代表不同的组合,所以不能先遍历物品再遍历背包,因为先遍历物品再遍历背包得出的结果顺序都是和原来的顺序相同,不能体现不同的顺序
  • 所以必须先遍历背包容量再遍历物品,这样相同的物品可能出现在前,也可能出现在后

代码:

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