15% off all plans & roadmaps Use code
See plansCoin Change II
- LeetCode 518
- Medium
- Dynamic Programming (DP) Patterns
- 1D Array (Coin Change / Unbounded Knapsack Style)
Updated
TL;DR: Count how many unordered combinations of unlimited coins add up to a target. Put coins on the outer loop and amounts on the inner loop of a 1D DP array so each combination is counted once.
Problem
You are given an integer array coins holding coin denominations and an integer amount holding a target sum of money.
Return the number of combinations of coins that add up to amount. If no combination of the coins can make that amount, return 0.
You have an unlimited supply of every kind of coin. The answer is guaranteed to fit in a signed 32-bit integer.
Example 1
Input: amount = 5, coins = [1,2,5] Output: 4 Explanation: there are four ways to make the amount: - 5 = 5 - 5 = 2 + 2 + 1 - 5 = 2 + 1 + 1 + 1 - 5 = 1 + 1 + 1 + 1 + 1
Example 2
Input: amount = 3, coins = [2] Output: 0 Explanation: the amount 3 cannot be made using only coins of value 2.
Example 3
Input: amount = 10, coins = [10] Output: 1
Constraints
1 <= coins.length <= 3001 <= coins[i] <= 5000- All values in
coinsare unique. 0 <= amount <= 5000
Constraints that matter
- amount up to 5000 and up to 300 coins means a table of about 1.5 million cells is fine. O(n * amount) time is the target, roughly 1.5 million operations.
- Plain recursion branches on every coin at every step. With coin 1 and amount 5000 the recursion tree is far too large, so you must reuse subproblem answers.
- Coin values can be as large as 5000 and are all at least 1, so every step shrinks the remaining amount. Recursion and DP both terminate, and no coin can loop forever.
- amount can be 0, and the answer is then 1 (choose no coins). The base case dp[0] = 1 must be handled explicitly.
- The final answer fits in 32 bits, but intermediate table cells might not in every language. Use wrapping arithmetic or wider types so no cell causes undefined behavior.
Hints
Hint 1
This is an unbounded knapsack counting problem, solved with dynamic programming.
Hint 2
Try every choice for each coin.
Solution
Intuition
This is an unbounded knapsack counting problem, solved with dynamic programming. Each coin can be used any number of times, and you count ways instead of picking a best value. The question to ask is: how many ways can I reach amount j using only the first few coins?
Picture a row of mailboxes, one per amount from 0 to the target, where box j holds the count of ways to reach j. For each coin, you walk left to right and add the count from the box c slots to the left into each box, so the row itself is the dp array and the walk is the update.
The catch is that order must not matter. 2+3 and 3+2 are one combination. If you let every amount choose any coin as its last coin, you count permutations, which is a different problem (Combination Sum IV).
The fix is to decide coin by coin. Pick a coin order once, then for each coin decide how many copies to use. A combination is then generated in exactly one way: all copies of the first coin, then all copies of the second, and so on.
That gives a clean recurrence. Let ways(i, j) be the number of combinations of the first i coins that sum to j. Either you never use coin i, giving ways(i-1, j), or you use it at least once, giving ways(i, j - coin). The second term keeps i the same because the coin is reusable.
Worked example
Input: amount = 10, coins = [2, 3, 5, 6] Output: 5 Explanation: The five combinations are 5+5, 2+3+5, 2+2+6, 2+2+3+3 and 2+2+2+2+2. Order does not matter, so 2+3+5 and 5+3+2 count once.
Approach 1: Brute force recursion
Try every choice for each coin. At coin index i with rem left to make, you either take one more copy of coin i (stay at index i, subtract the coin) or skip coin i forever (move to index i + 1).
Staying at the same index on the take branch is what allows reuse. Moving forward on the skip branch stops 1+2 and 2+1 from both being counted. When rem hits 0 you have found one combination. When rem goes negative or you run out of coins, that path counts 0.
Steps
- Define count(i, rem) as the number of combinations using coins from index i onward that sum to rem.
- If rem is 0, return 1.
- If rem is negative or i equals the number of coins, return 0.
- Return count(i, rem - coins[i]) plus count(i + 1, rem).
- Call count(0, amount) and return the result.
Dry run
Trace amount = 10, coins = [2, 3, 5, 6]. The top call count(0, 10) splits into count(0, 8) (take a 2) and count(1, 10) (never use 2).
Each branch splits again until rem reaches 0, goes negative, or the coins run out. The paths that reach rem = 0 are exactly: 2+2+2+2+2, 2+2+3+3, 2+2+6, 2+3+5 and 5+5.
That is 5 leaves returning 1, and every other path returns 0. The sum at the root is 5, which matches the expected output. Note that count(1, 4) is reached by several different paths, such as 2+2 and via skipping, and each time it recomputes the same answer.
Complexity
| Time | O(2^(n + amount)) in the worst case |
|---|---|
| Space | O(n + amount) recursion depth |
Here n is the number of coins. Every call makes two further calls, and the depth can reach about amount (taking coin 1 repeatedly) plus n (skipping coins), so the call tree can have exponentially many nodes. The same pair (i, rem) is reached through many paths and recomputed each time. Only the call stack uses memory, and its depth is at most amount + n.
PythonTested in our runner
import sys
from typing import List, Optional
sys.setrecursionlimit(20000)
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
n = len(coins)
def count(i: int, rem: int) -> int:
if rem == 0:
return 1
if rem < 0 or i == n:
return 0
# take one more copy of coins[i], or never use coins[i] again
return count(i, rem - coins[i]) + count(i + 1, rem)
return count(0, amount)JavaTested in our runner
import java.util.*;
class Solution {
public int change(int amount, int[] coins) {
return count(coins, 0, amount);
}
private int count(int[] coins, int i, int rem) {
if (rem == 0) return 1;
if (rem < 0 || i == coins.length) return 0;
// take one more copy of coins[i], or never use coins[i] again
return count(coins, i, rem - coins[i]) + count(coins, i + 1, rem);
}
}C++Tested in our runner
class Solution {
public:
int change(int amount, vector<int>& coins) {
return count(coins, 0, amount);
}
private:
int count(vector<int>& coins, int i, int rem) {
if (rem == 0) return 1;
if (rem < 0 || i == (int)coins.size()) return 0;
// take one more copy of coins[i], or never use coins[i] again
return count(coins, i, rem - coins[i]) + count(coins, i + 1, rem);
}
};JavaScriptTested in our runner
/**
* @param {number} amount
* @param {number[]} coins
* @return {number}
*/
var change = function(amount, coins) {
const n = coins.length;
const count = (i, rem) => {
if (rem === 0) return 1;
if (rem < 0 || i === n) return 0;
// take one more copy of coins[i], or never use coins[i] again
return count(i, rem - coins[i]) + count(i + 1, rem);
};
return count(0, amount);
};GoTested in our runner
func change(amount int, coins []int) int {
n := len(coins)
var count func(i, rem int) int
count = func(i, rem int) int {
if rem == 0 {
return 1
}
if rem < 0 || i == n {
return 0
}
// take one more copy of coins[i], or never use coins[i] again
return count(i, rem-coins[i]) + count(i+1, rem)
}
return count(0, amount)
}C#Tested in our runner
public class Solution {
public int change(int amount, int[] coins) {
return Count(coins, 0, amount);
}
private int Count(int[] coins, int i, int rem) {
if (rem == 0) return 1;
if (rem < 0 || i == coins.Length) return 0;
// take one more copy of coins[i], or never use coins[i] again
return Count(coins, i, rem - coins[i]) + Count(coins, i + 1, rem);
}
}Approach 2: 2D DP table
What's slow: the recursion answers the same (i, rem) question many times. There are only (n + 1) * (amount + 1) distinct pairs, so almost all of the work is repeated.
The insight that fixes it: store each answer once, and fill the table in an order where the answers you need already exist. Let dp[i][j] be the number of combinations of the first i coins that make j. Then dp[i][j] = dp[i-1][j] + dp[i][j - coin], where the second term applies only when j >= coin.
Steps
- Create a table dp with n + 1 rows and amount + 1 columns, filled with 0.
- Set dp[i][0] = 1 for every row, since choosing no coins makes amount 0.
- For each row i from 1 to n, let c be coins[i - 1].
- For each column j from 1 to amount, start with dp[i][j] = dp[i-1][j].
- If j >= c, add dp[i][j - c] to dp[i][j].
- Return dp[n][amount].
Dry run
Trace amount = 10, coins = [2, 3, 5, 6]. Columns are amounts 0 to 10. Row 0 is [1,0,0,0,0,0,0,0,0,0,0].
- After coin 2:
[1,0,1,0,1,0,1,0,1,0,1](only even amounts work). - After coin 3:
[1,0,1,1,1,1,2,1,2,2,2]. For example, dp[6] = 1 (from 2s) + dp[3] = 1 gives 2. - After coin 5:
[1,0,1,1,1,2,2,2,3,3,4]. For example, dp[10] = 2 + dp[5] = 2 gives 4. - After coin 6:
[1,0,1,1,1,2,3,2,4,4,5]. dp[10] = 4 + dp[4] = 1 gives 5.
The last row ends in 5, which matches the expected output.
Complexity
| Time | O(n * amount) |
|---|---|
| Space | O(n * amount) |
Here n is the number of coins. The table has (n + 1) * (amount + 1) cells and each cell takes one addition, so the time is O(n * amount), at most about 1.5 million operations. The table is the dominant memory cost, so space is also O(n * amount).
PythonTested in our runner
from typing import List, Optional
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
n = len(coins)
# dp[i][j] = ways to make j using the first i coins
dp = [[0] * (amount + 1) for _ in range(n + 1)]
for i in range(n + 1):
dp[i][0] = 1
for i in range(1, n + 1):
c = coins[i - 1]
for j in range(1, amount + 1):
dp[i][j] = dp[i - 1][j] # never use coin i
if j >= c:
dp[i][j] += dp[i][j - c] # use coin i at least once
return dp[n][amount]JavaTested in our runner
import java.util.*;
class Solution {
public int change(int amount, int[] coins) {
int n = coins.length;
// dp[i][j] = ways to make j using the first i coins
int[][] dp = new int[n + 1][amount + 1];
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
for (int i = 1; i <= n; i++) {
int c = coins[i - 1];
for (int j = 1; j <= amount; j++) {
dp[i][j] = dp[i - 1][j]; // never use coin i
if (j >= c) {
dp[i][j] += dp[i][j - c]; // use coin i at least once
}
}
}
return dp[n][amount];
}
}C++Tested in our runner
class Solution {
public:
int change(int amount, vector<int>& coins) {
int n = coins.size();
// unsigned so intermediate wraparound is well defined
vector<vector<unsigned int>> dp(n + 1, vector<unsigned int>(amount + 1, 0));
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
for (int i = 1; i <= n; i++) {
int c = coins[i - 1];
for (int j = 1; j <= amount; j++) {
dp[i][j] = dp[i - 1][j]; // never use coin i
if (j >= c) {
dp[i][j] += dp[i][j - c]; // use coin i at least once
}
}
}
return (int)dp[n][amount];
}
};JavaScriptTested in our runner
/**
* @param {number} amount
* @param {number[]} coins
* @return {number}
*/
var change = function(amount, coins) {
const n = coins.length;
// dp[i][j] = ways to make j using the first i coins
const dp = [];
for (let i = 0; i <= n; i++) {
dp.push(new Int32Array(amount + 1));
dp[i][0] = 1;
}
for (let i = 1; i <= n; i++) {
const c = coins[i - 1];
for (let j = 1; j <= amount; j++) {
let v = dp[i - 1][j]; // never use coin i
if (j >= c) {
v = (v + dp[i][j - c]) | 0; // use coin i at least once
}
dp[i][j] = v;
}
}
return dp[n][amount];
};GoTested in our runner
func change(amount int, coins []int) int {
n := len(coins)
// dp[i][j] = ways to make j using the first i coins
dp := make([][]int32, n+1)
for i := range dp {
dp[i] = make([]int32, amount+1)
dp[i][0] = 1
}
for i := 1; i <= n; i++ {
c := coins[i-1]
for j := 1; j <= amount; j++ {
dp[i][j] = dp[i-1][j] // never use coin i
if j >= c {
dp[i][j] += dp[i][j-c] // use coin i at least once
}
}
}
return int(dp[n][amount])
}C#Tested in our runner
public class Solution {
public int change(int amount, int[] coins) {
int n = coins.Length;
// dp[i][j] = ways to make j using the first i coins
int[][] dp = new int[n + 1][];
for (int i = 0; i <= n; i++) {
dp[i] = new int[amount + 1];
dp[i][0] = 1;
}
for (int i = 1; i <= n; i++) {
int c = coins[i - 1];
for (int j = 1; j <= amount; j++) {
dp[i][j] = dp[i - 1][j]; // never use coin i
if (j >= c) {
unchecked { dp[i][j] += dp[i][j - c]; } // use coin i at least once
}
}
}
return dp[n][amount];
}
}
Solution pattern
1D Array (Coin Change / Unbounded Knapsack Style)
Approach 3: 1D DP arrayOptimal1D Array (Coin Change / Unbounded Knapsack Style)
What's slow: the 2D table keeps every row, but row i reads only row i - 1 (same column) and row i itself (earlier column). Older rows are never touched again, so most of the memory is wasted.
The insight that fixes it: keep a single row and update it in place, coin by coin. When you process a coin, dp[j] still holds the old row value (dp[i-1][j]) before you add to it. The cell dp[j - c] was already updated in this pass, so it holds dp[i][j - c]. Looping j upward therefore lets the same coin be reused.
Why it is correct. After processing the first i coins, dp[j] holds the number of combinations of those coins that sum to j. When coin c is processed, every combination that uses it has at least one copy, so removing one copy leaves a valid combination for amount j minus c. Because j increases, dp[j - c] already includes all uses of c, so each combination is counted exactly once and order never matters.
Steps
- Create dp of size amount + 1 filled with 0, and set dp[0] = 1.
- Loop over each coin c in coins. This outer loop is what makes the count ignore order.
- Loop j from c up to amount, in increasing order.
- Update dp[j] += dp[j - c].
- After all coins are processed, return dp[amount].
Dry run
Trace amount = 10, coins = [2, 3, 5, 6]. The array starts as dp = [1,0,0,0,0,0,0,0,0,0,0]. Each row below is the array after one full pass over a coin.
| Step | Coin | Updates (j: old + dp[j-c] = new) | dp after the pass (index 0..10) |
|---|---|---|---|
| 0 | start | none | 1,0,0,0,0,0,0,0,0,0,0 |
| 1 | 2 | 2: 0+1=1, 4: 0+1=1, 6: 0+1=1, 8: 0+1=1, 10: 0+1=1 (odd j add 0) | 1,0,1,0,1,0,1,0,1,0,1 |
| 2 | 3 | 3: 0+1=1, 4: 1+0=1, 5: 0+1=1, 6: 1+1=2, 7: 0+1=1, 8: 1+1=2, 9: 0+2=2, 10: 1+1=2 | 1,0,1,1,1,1,2,1,2,2,2 |
| 3 | 5 | 5: 1+1=2, 6: 2+0=2, 7: 1+1=2, 8: 2+1=3, 9: 2+1=3, 10: 2+2=4 | 1,0,1,1,1,2,2,2,3,3,4 |
| 4 | 6 | 6: 2+1=3, 7: 2+0=2, 8: 3+1=4, 9: 3+1=4, 10: 4+1=5 | 1,0,1,1,1,2,3,2,4,4,5 |
The answer is dp[10] = 5. During the coin 3 pass, dp[6] reads dp[3], which was updated moments earlier in the same pass. That is how 3+3 becomes possible.
Complexity
| Time | O(n * amount) |
|---|---|
| Space | O(amount) |
Here n is the number of coins. The outer loop runs n times and the inner loop runs at most amount times, with one addition per iteration, so time is O(n * amount). The only structure is dp with amount + 1 entries, so space is O(amount).
Correctness follows by induction on the coins. Before coin k, dp[j] counts combinations of the first k - 1 coins. After the pass, dp[j] adds the combinations that use coin k at least once, which equal the ways to make j - c with the first k coins.
PythonTested in our runner
from typing import List, Optional
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
dp = [0] * (amount + 1)
dp[0] = 1 # one way to make 0: take nothing
for c in coins: # coins outside, so order never matters
for j in range(c, amount + 1): # ascending allows reuse of c
dp[j] += dp[j - c]
return dp[amount]JavaTested in our runner
import java.util.*;
class Solution {
public int change(int amount, int[] coins) {
int[] dp = new int[amount + 1];
dp[0] = 1; // one way to make 0: take nothing
for (int c : coins) { // coins outside, so order never matters
for (int j = c; j <= amount; j++) { // ascending allows reuse of c
dp[j] += dp[j - c];
}
}
return dp[amount];
}
}C++Tested in our runner
class Solution {
public:
int change(int amount, vector<int>& coins) {
// unsigned so intermediate wraparound is well defined
vector<unsigned int> dp(amount + 1, 0);
dp[0] = 1; // one way to make 0: take nothing
for (int c : coins) { // coins outside, so order never matters
for (int j = c; j <= amount; j++) { // ascending allows reuse of c
dp[j] += dp[j - c];
}
}
return (int)dp[amount];
}
};JavaScriptTested in our runner
/**
* @param {number} amount
* @param {number[]} coins
* @return {number}
*/
var change = function(amount, coins) {
const dp = new Int32Array(amount + 1);
dp[0] = 1; // one way to make 0: take nothing
for (const c of coins) { // coins outside, so order never matters
for (let j = c; j <= amount; j++) { // ascending allows reuse of c
dp[j] = (dp[j] + dp[j - c]) | 0;
}
}
return dp[amount];
};GoTested in our runner
func change(amount int, coins []int) int {
dp := make([]int32, amount+1)
dp[0] = 1 // one way to make 0: take nothing
for _, c := range coins { // coins outside, so order never matters
for j := c; j <= amount; j++ { // ascending allows reuse of c
dp[j] += dp[j-c]
}
}
return int(dp[amount])
}C#Tested in our runner
public class Solution {
public int change(int amount, int[] coins) {
int[] dp = new int[amount + 1];
dp[0] = 1; // one way to make 0: take nothing
foreach (int c in coins) { // coins outside, so order never matters
for (int j = c; j <= amount; j++) { // ascending allows reuse of c
unchecked { dp[j] += dp[j - c]; }
}
}
return dp[amount];
}
}Common mistakes
- Putting the amount loop outside and the coin loop inside (
for j ... for c in coins). That counts ordered sequences, so 1+2 and 2+1 both count. Swap the loops so coins are on the outside. - Forgetting
dp[0] = 1. Every cell is built by adding earlier cells, so an all-zero array stays all zeros. Set the base case to 1 before any coin is processed. - Looping
jdownward fromamounttoc. That is the 0/1 knapsack pattern and lets each coin be used at most once. Loop upward sodp[j - c]already includes this coin. - Starting the inner loop at 0 or 1 instead of
c. Thendp[j - c]reads a negative index. Start atj = c, or guard withif j >= c. - In the recursive version, writing
count(i + 1, rem - coins[i])for the take branch. That limits each coin to one use. Keepithe same when you take a coin. - Checking
rem < 0after the coin lookup in the recursion, or testingi == nbeforerem == 0. Withrem == 0and no coins left you must still return 1, so testrem == 0first.
Edge cases
amount = 0with any coins: return 1, the empty combination.coins = [2],amount = 3: return 0, because no sum of 2s equals an odd number.coins = [10],amount = 10: return 1, a single coin that matches exactly.coins = [1]withamount = 5000: return 1, one combination of 5000 ones, and the loop must not overflow or recurse too deeply in the DP versions.- A coin larger than the amount, such as
coins = [7, 1],amount = 5: the 7 contributes nothing and the answer is 1. The inner loop must not run for that coin. - Many small coins, such as
[1, 2, 3, ...]with a large amount: counts grow fast, so use wrapping or wide arithmetic for intermediate cells.
Follow-ups interviewers ask
- How would you count ordered sequences (permutations) instead of combinations?
- Swap the loops. Put amount on the outside and coins on the inside, and keep dp[j] += dp[j - c]. Now each amount can end with any coin, so 1+2 and 2+1 are counted separately. This is Combination Sum IV.
- How would you find the fewest coins instead of counting ways?
- Keep the same loop structure but change the cell meaning to the minimum coin count. Initialize dp[0] = 0 and the rest to infinity, then use dp[j] = min(dp[j], dp[j - c] + 1). Return -1 if dp[amount] is still infinity. This is Coin Change.
- What if each coin can be used at most once?
- Iterate j downward from amount to c in the inner loop. Going downward means dp[j - c] has not yet been updated by this coin, so the coin is counted at most once per combination. This is the 0/1 knapsack version. The complexity stays O(n * amount) time and O(amount) space.
Coin Change II FAQ
What is the time complexity of Coin Change II?
O(n * amount), where n is the number of coins. The outer loop visits each coin once and the inner loop visits at most amount + 1 cells, doing one addition each. Space for the 1D version is O(amount).
Why use dynamic programming for Coin Change II?
The number of ways to make amount j depends on the number of ways to make smaller amounts, and the same smaller amounts are needed again and again. Plain recursion recomputes them exponentially often. A DP array stores each answer once, cutting the work to O(n * amount).
Why does the coin loop go on the outside in Coin Change II?
It fixes the order in which coin types are added. Each combination is built as all copies of the first coin, then the second, and so on, so it appears exactly once. With amounts on the outside, every order is generated and you count permutations instead.
Can Coin Change II be solved in O(1) extra space?
No, not with this approach. The DP needs one counter per amount from 0 to amount, which is O(amount) space. The recursion uses less table memory but takes exponential time, so O(amount) is the practical minimum.
Why does dp[0] equal 1 in Coin Change II?
There is exactly one way to make amount 0, which is to use no coins. Every other cell is built by adding dp[j - c], so a base of 1 is what seeds all counts. It also gives the correct answer 1 when the target amount is 0.
Is there a gotcha with integer overflow in Coin Change II?
The final answer fits in a signed 32-bit integer, but the problem does not promise that every intermediate cell does. In Java and C# int addition wraps, and the final result is still correct because only additions are used. In C++ use unsigned int to avoid undefined behavior, and in JavaScript wrap with | 0. Python integers never overflow.
Asked at
See which companies ask this — Pro
Related problems
- Coin Change · same technique: 1D Array (Coin Change / Unbounded Knapsack Style)
- Combination Sum IV · same technique: 1D Array (Coin Change / Unbounded Knapsack Style)
- Perfect Squares · same technique: 1D Array (Coin Change / Unbounded Knapsack Style)
- Distinct Subsequences · next harder, same pattern
- Maximum Subarray · same pattern: Dynamic Programming (DP) Patterns
- Word Break · same pattern: Dynamic Programming (DP) Patterns
- Longest Increasing Subsequence · same pattern: Dynamic Programming (DP) Patterns
- Edit Distance · same pattern: Dynamic Programming (DP) Patterns
- House Robber · same pattern: Dynamic Programming (DP) Patterns
- Longest Common Subsequence · same pattern: Dynamic Programming (DP) Patterns