DSA problem
Coin Change II
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0. You may assume that you have an infinite number of each kind of coin, and the answer is guaranteed to fit into a signed 32-bit integer.
This problem is the counting twin of the classic Coin Change problem: instead of asking for the minimum number of coins, it asks how many distinct unordered combinations sum to amount. Because combinations are unordered, {1, 2} and {2, 1} are the same combination and must be counted only once — this constraint is exactly what makes the loop order critical.
Define dp[a] as the number of unordered combinations that sum to amount a. The base case is dp[0] = 1 because the empty multiset is the one and only combination summing to zero. The recurrence is dp[a] += dp[a - coin], but the order of loops matters: the coin denominations must be the outer loop and the amount the inner loop, both iterating in ascending order. This guarantees that for each coin, we only extend combinations that have already finished considering the previous coins, so we count each combination exactly once.
If you swap the loops — amount outer, coin inner — you instead count ordered sequences (permutations), which over-counts. The combinations algorithm runs in O(amount * len(coins)) time and O(amount) space. The key insight is "coins outer, amount ascending inner" — the canonical loop ordering for unbounded-knapsack counting.
Examples
amount = 5, coins = [1,2,5]4amount = 3, coins = [2]0amount = 10, coins = [10]1Constraints
- 1 <= coins.length <= 300
- 1 <= coins[i] <= 5000
- All the values of coins are unique.
- 0 <= amount <= 5000
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.