Coin Change II
The key idea
Count combinations, not permutations: loop over coins on the OUTSIDE and amounts on the INSIDE. Fixing the coin order means 1+2 and 2+1 are never counted twice.
dp[x] accumulates the number of ways to make x using only the coins processed so far, and dp[x] += dp[x - coin] reuses each coin unlimited times.Problem
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.
The answer is guaranteed to fit into a signed 32-bit integer.
Constraints
1 <= coins.length <= 3001 <= coins[i] <= 5000- All the values of
coinsare unique. 0 <= amount <= 5000
Examples
Input: amount = 5, coins = [1,2,5]
Output: 4
Input: amount = 3, coins = [2]
Output: 0
Input: amount = 10, coins = [10]
Output: 1
Complexity
Time: O(n * amount) Space: O(amount)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Dynamic Programming problems
- Best Time to Buy and Sell StockEASY
- Best Time to Buy and Sell Stock IIIHARD
- Best Time to Buy and Sell Stock IVHARD
- Best Time to Buy and Sell Stock with CooldownMEDIUM
- Best Time to Buy and Sell Stock with Transaction FeeMEDIUM
- Burst BalloonsHARD
- Climbing StairsEASY
- Coin ChangeMEDIUM
- Combination Sum IVMEDIUM
- Counting BitsEASY
- Decode WaysMEDIUM
- Delete Operation for Two StringsMEDIUM