sagelearnai

Coin Change II

Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #518

Count the number of combinations (order doesn't matter) of coins from coins (unlimited supply) that sum to amount. amount = 0 has exactly one combination: no coins.

Examples

text
amount = 5, coins = [1, 2, 5]   →  4    (5 · 2+2+1 · 2+1+1+1 · 1+1+1+1+1)
amount = 3, coins = [2]         →  0
amount = 10, coins = [10]       →  1

Hints

  1. Conceptually dp[i][a] = ways to make a using the first i coin types; this compresses to 1-D.
  2. The loop order matters: coins in the outer loop count combinations; amounts in the outer loop would count ordered sequences (permutations).

Approach

dp[a] = number of combinations summing to a using the coin types processed so far, with dp[0] = 1. For each coin c (outer loop) and each a from c up to amount (inner loop, ascending, since reuse is allowed): dp[a] += dp[a − c].

Because each coin type is fully processed before the next, every combination is counted once, in a canonical order of coin types. Swapping the loops would count 1+2 and 2+1 separately.

Complexity

Time: O(amount × len(coins)). Space: O(amount).

Python solution
def change(amount, coins):
    dp = [1] + [0] * amount
    for c in coins:
        for a in range(c, amount + 1):
            dp[a] += dp[a - c]
    return dp[amount]
JavaScript solution
function change(amount, coins) {
  const dp = new Array(amount + 1).fill(0); dp[0] = 1;
  for (const c of coins) for (let a = c; a <= amount; a++) dp[a] += dp[a - c];
  return dp[amount];
}