Coin Change II (LeetCode 518): Solution and Explanation
You are given coin denominations, with an unlimited supply of each, and a target amount. Count how many different combinations of coins add up to exactly that amount, where order does not matter.
Watch it run step by step
Try your own input and write the code →Intuition
A recursive brute force picks a coin, subtracts it and recurses, but it counts 1 + 2 and 2 + 1 as different, which the problem forbids. To count combinations instead of sequences, you have to impose an order on how coins are chosen, for example by only allowing coins at or after the current index. That recursion is correct but exponential without memoization.
Memoize it and flip it around, and you get a table where dp[i][a] counts the ways to make amount a using only the first i coins. Either you use no more of coin i, giving dp[i - 1][a], or you use at least one more, giving dp[i][a - coin]. Since each row only looks at the previous row and itself, one array suffices.
That is why the loop order matters so much. With coins in the outer loop and amounts in the inner loop, when you process coin c every combination is built by first deciding how many of the earlier coins to use and then how many copies of c. Each multiset of coins is counted exactly once. If you swap the loops, amounts outside and coins inside, you count every ordering separately, which solves a different problem (the number of sequences). Iterating amounts upward within a coin is what allows reusing the same coin many times.
A useful sanity check is to think about what dp[a - coin] means at the moment you read it. Because the inner loop moves upward, that entry has already been updated for the current coin, so it counts combinations that may already include this coin. Adding it to dp[a] therefore means adding one more copy of the coin to every such combination, which is exactly the unlimited supply rule.
Approach: Unbounded knapsack counting DP
- Create
dpof sizeamount + 1filled with 0, wheredp[a]is the number of ways to form a. - Set
dp[0] = 1, since there is exactly one way to make zero: use no coins. - Loop over each
coinin the outer loop. - For each amount
afromcoinup toamount, adddp[a - coin]todp[a]. - Return
dp[amount].
Step-by-step example
amount = 5, coins = [1, 2, 5]
- Start with
dp = [1, 0, 0, 0, 0, 0]. - Coin 1: each amount can be made only with ones, so
dp = [1, 1, 1, 1, 1, 1]. - Coin 2:
dp[2] = 1 + dp[0] = 2,dp[3] = 1 + dp[1] = 2,dp[4] = 1 + dp[2] = 3,dp[5] = 1 + dp[3] = 3, giving[1, 1, 2, 2, 3, 3]. - Coin 5:
dp[5] = 3 + dp[0] = 4. - The answer is 4: 5, 2 + 2 + 1, 2 + 1 + 1 + 1 and 1 + 1 + 1 + 1 + 1.
Code: Python, Java, C++
1class Solution:
2 def change(self, amount: int, coins: List[int]) -> int:
3 dp = [0] * (amount + 1)
4 dp[0] = 1
5
6 for coin in coins:
7 for a in range(coin, amount + 1):
8 dp[a] += dp[a - coin]
9
10 return dp[amount]1class Solution {
2 public int change(int amount, int[] coins) {
3 int[] dp = new int[amount + 1];
4 dp[0] = 1;
5
6 for (int coin : coins) {
7 for (int a = coin; a <= amount; a++) {
8 dp[a] += dp[a - coin];
9 }
10 }
11 return dp[amount];
12 }
13}1class Solution {
2public:
3 int change(int amount, vector<int>& coins) {
4 vector<int> dp(amount + 1, 0);
5 dp[0] = 1;
6
7 for (int coin : coins) {
8 for (int a = coin; a <= amount; a++) {
9 dp[a] += dp[a - coin];
10 }
11 }
12 return dp[amount];
13 }
14};Time and space complexity
O(n × amount)
For each of the n coins, the inner loop runs over at most amount + 1 values with constant work.
O(amount)
A single array of length amount + 1 holds the counts, reused across coins.
Other approaches
2D DP table (time O(n × amount), space O(n × amount))
Store dp[i][a] for every prefix of coins and every amount. It makes the recurrence easy to see and debug, but uses n times more memory.
Top-down memoized recursion (time O(n × amount), space O(n × amount))
Recurse on (index, remaining), choosing to use coin index again or move to the next coin, and cache results. Natural to derive but deeper recursion and more overhead.
Common mistakes
- Swapping the loops (amounts outer, coins inner) counts permutations, so the example would return 9 instead of 4.
- Iterating amounts downward from
amounttocointurns it into the 0/1 knapsack, where each coin can be used at most once. - Initializing
dp[0] = 0makes every count zero; the empty combination must count as one way. - Confusing this with Coin Change I and taking a minimum instead of a sum.
Frequently asked questions
Why does the loop order matter in Coin Change II?
Coins in the outer loop count each combination once, because coins are always added in a fixed order. Amounts in the outer loop count every ordering of the same coins separately.
What is the difference between Coin Change and Coin Change II?
Coin Change asks for the fewest coins to reach the amount, so it takes a minimum. Coin Change II asks for the number of combinations, so it adds counts.
Why is dp[0] equal to 1?
There is exactly one way to make an amount of zero, which is to choose no coins. Every combination ultimately builds on that base case.
What is the time complexity of Coin Change II?
O(n × amount), where n is the number of coin types. The space is O(amount) with the one-dimensional array. Since the amount is at most 5,000 and there are at most 300 coins, that is about 1.5 million simple additions.