LeetCode刷题 Day44
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.
Example 1:
Input: amount = 5, coins = [1,2,5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
Example 2:
Input: amount = 3, coins = [2]
Output: 0
Explanation: the amount of 3 cannot be made up just with coins of 2.
Example 3:
Input: amount = 10, coins = [10]
Output: 1
思路: 这是一个完全背包组合问题,所以: 1. 要考虑遍历顺序 2. 要考虑递推公式
步骤:
-
dp index和value意义: index为背包容量,value为该背包容量下的组合个数
-
递推公式: 因为是求组合个数,所以可以使用 dp[j] += dp[j - coins[i]];
-
dp初始化: dp[0] = 1,背包为0的情况填满背包有一种组合, 其余为0
-
遍历顺序: 因为是完全背包问题,所以要考虑重复加入的问题,背包的遍历为正序遍历 而两个for loop的内外顺序是不能随意调换的: 当背包遍历在内的时候,就会变成计算排列数
**如果求组合数就是外层for循环遍历物品,内层for遍历背包**。 **如果求排列数就是外层for遍历背包,内层for循环遍历物品**。 -
举例论证:
代码:
var change = function(amount, coins) {
let dp = Array(amount + 1).fill(0);
dp[0] = 1;
for (let coin of coins) {
for (let j = coin; j <= amount; j++) {
dp[j] += dp[j - coin]
}
}
return dp[amount];
};
时间复杂度: O(n*m) n为物品数组大小, m为背包大小 空间复杂度: O(m)
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.
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
思路: 因为是计算排列的问题,所以要注意内层和外层loop的顺序
步骤:
- dp index和value意义: index 是背包size,value是当前背包下的排列数
- 递推公式: dp[i] += dp[i - num];
- 初始化: dp[0] = 1;
- 遍历顺序: 外层为背包,内层为物品
- 举例论证:
代码:
var combinationSum4 = function(nums, target) {
let dp = Array(target + 1).fill(0);
dp[0] = 1;
for (let i = 0; i <= target; i++) {
for (let num of nums) {
if (i - num >= 0) {
dp[i] += dp[i - num];
}
}
}
return dp[target];
};
时间复杂度: O(nm) 空间复杂度: O(n)