518. Coin Change 2
https://leetcode.com/problems/coin-change-2/
2D
dp[i - 1][j]
: means the number of combinations if we compeletly don't use the ith
coin
dp[i][j - coins[i - 1]]
: we must use at least one of the ith
coin, so we expell the ith
coin from j (Exclusive, opposite to the upper condition)
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
m = len(coins)
n = amount
dp = [[0]*(n+1) for _ in range(m+1)]
dp[0][0] = 1
for i in range(1,m+1):
for j in range(n+1):
dp[i][j] = dp[i-1][j]
if j >= coins[i-1]:
dp[i][j] += dp[i][j-coins[i-1]]
return dp[m][n]
1D:
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
m = len(coins)
n = amount
dp = [0] *(amount+1)
dp[0] = 1
for coin in coins:
for i in range(coin,amount+1):
dp[i] += dp[i-coin]
return dp[amount]
Last updated
Was this helpful?