518. Change for II
Answer:
-
Assume that amount = 5, Coins = [1, 2, 5] is entered. If the dp array with length of amount + 1 is used for recursion, the following characteristics must be met:
- If I take the length of theta
amount + 1
thedp
Array recursion. - Each index represents the amount recurred to.
- Each element is the number of combinations of coins.
0
The position is the initial state, set to1
, indicates that both from1
The number of combinations starts to recurse.
- If I take the length of theta
-
We can break it down by coin type recursively:
- COINS
1
:,1,1,1,1,1 [1]
- COINS
2
:,0,1,0,1,0 [1]
- COINS
5
:,0,0,0,0,1 [1]
- COINS
1
,2
:,1,2,2,3,3 [1]
- COINS
1
,2
,5
:,1,2,2,3,4 [1]
- COINS
-
The recursive method is as follows:
- Count each coin denomination in turn
coin
Is the recursive result of. - The current amount
i
From thei - coin
addedcoin
And come. - Number of current coin combinations
dp[i]
Theta is the same thing as the last coini
The combination of severaldp[i]
, plusi - coin
The combination of severaldp[i - coin]
And come. - The state transition equation is:
dp[i] = dp[i] + dp[i - coin]
.
- Count each coin denomination in turn
/ * * *@param {number} amount
* @param {number[]} coins
* @return {number}* /
var change = function (amount, coins) {
// Keep using coin combinations from 0 to amount
// The array holds the number of coin combinations available for each amount
// The initial state is 0 because there is no recursion
let dp = new Array(amount + 1).fill(0);
// Set position 0 to 1, since the first push starts with the amount of coin
// the state transition equation is dp[I] = dp[I] + dp[i-coin].
// Dp [0] = 1
dp[0] = 1;
// Count the number of ways each coin can be combined into an amount
for (const coin of coins) {
// An amount less than coin cannot be combined by coin
// Push all the way to amount to see how many ways the current coin can be combined to form amount
for (let i = coin; i <= amount; i++) {
dp[i] =
// The number of ways in which coins can be combined to create the current amount
dp[i] +
// The current amount must be a combination of i-coins and coins added
// That is, the current amount is based on i-coins, so you need to bring the number of i-coins combineddp[i - coin]; }}// The number of methods that are finally combined to amount, at the amount location
return dp[amount];
};
Copy the code