dp[j] represents the number of ways to make amount j. We process coins one at a time (outer loop) to avoid counting permutations as different combinations.
- Create
dparray of sizeamount + 1, initialized to 0. dp[0] = 1(one way to make amount 0: use no coins).- For each coin:
- For each amount from
cointoamount:dp[j] += dp[j - coin].
- For each amount from
- Return
dp[amount].
- Time Complexity: O(amount * len(coins)).
- Space Complexity: O(amount).
def change(amount, coins):
dp = [0] * (amount + 1)
dp[0] = 1
for coin in coins:
for j in range(coin, amount + 1):
dp[j] += dp[j - coin]
return dp[amount]