You have coins of a few different values, listed in coins, and as many of each value as you want. Count the different ways to pay exactly amount.
A way is a mix of coins: how many of each value you use. The order does not matter, so 1 + 2 and 2 + 1 are the same way. If the amount cannot be paid, the answer is 0. The answer fits in a 32-bit signed integer.
Example 1
Input: amount = 4, coins = [1, 2, 3] Output: 4 Why: 1+1+1+1, 1+1+2, 2+2 and 1+3
2 more examples and the constraints
Example 2
Input: amount = 7, coins = [2, 4] Output: 0 Why: even coins never add up to an odd amount
Example 3
Input: amount = 0, coins = [6] Output: 1 Why: using no coins is the one way to pay 0
Constraints
- 1 ≤ length of coins ≤ 300
- 1 ≤ each coin ≤ 5,000, and no two coins have the same value
- 0 ≤ amount ≤ 5,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Plain recursionExponential
- Table: coins by amountO(n·k)
- One row, coins outsideO(n·k)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for amount 5,000 and 300 coins | Verdict |
|---|---|---|---|
| Plain recursion | Exponential | Shows the idea; far too slow | |
| Table: coins by amount | O(n·k) | Passes; more memory | |
| One row, coins outside | O(n·k) | Best; one short loop |
n = the amount, k = how many coin values there are.
Edge cases to test
- Amount 0. The answer is 1, the empty mix, whatever the coins are.
- Impossible amount. amount 7 with coins [2, 4] gives 0.
- Coin bigger than the amount. coins [5] and amount 3: the inner loop never runs, the answer is 0.
- Unsorted coins. [3, 1, 2] gives the same count as [1, 2, 3]; the order of the coin list does not matter.
Common mistakes
- Putting the amount loop outside and the coin loop inside, which counts 1 + 2 and 2 + 1 twice.
- Starting with dp[0] = 0, which makes every count 0.
- Walking the amounts downwards, which allows each coin at most once (the 0/1 knapsack).
How to talk through it
- 1Clarify. Does order matter? Can a coin repeat? What is the answer for amount 0?
- 2Give the recursion. Choose coins in list order so a mix is counted once; point out the repeated calls.
- 3Build the table. Skip the coin (cell above) or use it once more (c to the left).
- 4Squeeze to one row. Coins outside, amounts upwards inside: dp[a] += dp[a − c]. Say why the loop order matters.
- 5Test out loud. Run amount 0, an impossible amount, and Example 1 with the loops swapped to show the bug.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?