Coin Change II
Difficulty: Medium
Given coin denominations and a target amount, with unlimited coins of each kind, count the distinct combinations that add up to exactly amount.
Order doesn't matter — 2 then 3 is the same combination as 3 then 2.
Examples
Input: amount = 5, coins = [1,2,5]
Output: 4
5=5; 2+2+1; 2+1+1+1; 1+1+1+1+1.
Input: amount = 3, coins = [2]
Output: 0
No combination of 2s can ever total an odd number like 3.
Input: amount = 10, coins = [10]
Output: 1
Constraints
1 <= coins.length <= 300
1 <= coins[i] <= 5000
All coin values are distinct
0 <= amount <= 5000
Approach
Since order doesn't matter, use coin types as one dimension of the table and the amount as the other. Cell (i, a) is the number of combinations that make amount a using only the first i coin types.
Each cell adds two separate cases:
- Don't use the
i-th coin type: the count from one fewer coin type. - Use at least one: subtract the coin's value. Coins are reusable, so look at the same row at the smaller amount.
Looping over coin types on the outside (not amounts) ensures each combination is counted once — in the order its coin types appear in the list.
Solutions
Brute Force — Recursion
For each coin type, recursively branch on 'skip this coin type' versus 'use one more of it' (staying on the same type, since coins repeat). A remaining amount of exactly 0 is one valid combination.
function change(amount, coins) {
function countWays(i, remaining) {
if (remaining === 0) return 1;
if (remaining < 0 || i === coins.length) return 0;
const skipCoin = countWays(i + 1, remaining);
const useCoin = countWays(i, remaining - coins[i]);
return skipCoin + useCoin;
}
return countWays(0, amount);
}Time: O(2^amount) in the worst case · Space: O(amount) — recursion depth
Optimal — Bottom-Up 2D Table
Build a table with one row per coin type (plus a row for 'no coins yet') and one column per amount from 0 to the target. Each cell adds the 'skip this coin' and 'use this coin' counts.
function change(amount, coins) {
const n = coins.length;
const table = Array.from({ length: n + 1 }, () => new Array(amount + 1).fill(0));
for (let i = 0; i <= n; i++) {
table[i][0] = 1; // exactly one way to make amount 0: use no coins
}
for (let i = 1; i <= n; i++) {
for (let a = 1; a <= amount; a++) {
table[i][a] = table[i - 1][a]; // don't use this coin type at all
if (a - coins[i - 1] >= 0) {
table[i][a] += table[i][a - coins[i - 1]]; // use at least one of this coin type
}
}
}
return table[n][amount];
}Time: O(n * amount) · Space: O(n * amount)