Coin Change 2
You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.
Note:You can assume that
0 <= amount <= 5000
1 <= coin <= 5000
the number of coins is less than 500
the answer is guaranteed to fit into signed 32-bit integer
Thoughts:
dp[i][j]
: the number of combinations to make up amountj
by using the firsti
types of coinsState transition
:not using the
i
th coin, only using the firsti-1
coins to make up amountj
, then we havedp[i-1][j]
ways.
using the
i
th coin, since we can use unlimited same coin, we need to know how many way to make up amountj - coins[i]
by using firsti
coins( includingi
th), which isdp[i][j-coins[i]]
Initialization
:dp[i][0] = 1
dp[i][j]
only rely ondp[i-1][j]
anddp[i][j-coins[i]]
, then we can optimize the space by only using one-dimension array.
Code: 2D DP: O(K * N), S: O(K * N)
Code: 1D DP: O(K * N), S: O(N)
Last updated
Was this helpful?