Skip to content
DSA Patterns
Menu
Language
Knapsack & Subset DPLC #5184 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Coin Change II

Problem (restated)

Number of combinations that make up amount with given coin denominations (order does not matter).

Intuition

Outer loop coins, inner amount ascending → combinations not permutations.

Approaches

Unbounded knapsack count

Unverified
Time O(amount · n)Space O(amount)

Idea. dp[0]=1; for coin: for a=coin..amount: dp[a]+=dp[a-coin].

Walkthrough. amount=5, coins=[1,2,5] → 4.

Trade-offs. Swap loop order → permutations (wrong for this problem).

Solution
export function change(amount: number, coins: number[]): number {
  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]!;
}
export function change(amount: number, coins: number[]): number {
  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]!;
}

Template connection

The coin loop sits outside the amount loop, so order does not matter and coins may repeat. dp[0] = 1. For each coin, dp[a] += dp[a - coin] from that coin up to amount.

Reflection

  • For combinations, the coin is the outer loop and the amount is the inner loop. Swapping them counts permutations, so 1 + 2 and 2 + 1 both enter.
  • dp[0] = 1. Amount 0 answers 1. There is no coin of 0.
  • Order does not matter. The same coin may be used more than once while filling one amount.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Coin change II: combinations (order ignored) that sum to 5 with coins {1,2,5}.

0
0
1
1
2
2
3
3
4
4
5
5

dp[0]=1 · unbounded

Key:Active rangeMatchSettled