CodingNodes / 2-D Dynamic Programming / Coin Change II System design Space play · ←→ step · R restart

Problem

You are given a target amount of money and a list of distinct coin values coins. You have an unlimited supply of each coin.

Return how many different combinations of coins add up to exactly amount. Two combinations are the same if they use each coin the same number of times, regardless of order. If no combination works, return 0. The answer is guaranteed to fit in a 32-bit signed integer.

Constraints

  • 1 ≤ coins.length ≤ 300
  • 1 ≤ coins[i] ≤ 5000, all values distinct
  • 0 ≤ amount ≤ 5000

Examples: pick one to animate

Solutions

TimeO(n · amount) SpaceO(n · amount)

Time: The table has (n + 1) · (amount + 1) cells and each one is filled with one or two additions.

Space: The full table of (n + 1) rows and amount + 1 columns is stored.

Let dp[i][a] be the number of combinations that make a using only the first i coins. Either the last allowed coin is not used (dp[i-1][a]) or it is used at least once, and removing one copy leaves dp[i][a - coin]. Processing coins row by row counts each combination once, whatever its order.