Algo-Sim › Dynamic Programming
Coin Change II
Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input
Count the coin combinations that make an amount. Looping coins outside amounts counts each combination once, not every order.
Problem
Given an integer amount and an array of distinct coin values coins, return the number of combinations of coins that add up to amount. You have an unlimited supply of each coin, and combinations that differ only in order are the same. If no combination works, return 0.
Constraints
- 1 ≤ coins.length ≤ 300
- 1 ≤ coins[i] ≤ 5000, all distinct
- 0 ≤ amount ≤ 5000
- The answer fits in a 32-bit signed integer
Edge cases to test
- amount = 0:
1way - No coins can make it:
0 - A coin larger than the amount
Follow-up questions
- Why do loop orders matter?
- Coins outside counts combinations (each multiset once); amounts outside counts ordered sequences (Combination Sum IV).
- What is the space cost?
- One 1D array of size amount + 1: O(n·amount) time, O(amount) space.
Solution
Java
public int change(int amount, int[] coins) {
int[] dp = new int[amount + 1];
dp[0] = 1;
for (int coin : coins) {
for (int a = coin; a <= amount; a++) {
dp[a] += dp[a - coin];
}
}
return dp[amount];
}Python
def change(amount, coins):
dp = [0] * (amount + 1)
dp[0] = 1
for coin in coins:
for a in range(coin, amount + 1):
dp[a] += dp[a - coin]
return dp[amount]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int change(int amount, vector<int> &coins) {
vector<int> dp = vector<int>(amount + 1);
dp[0] = 1;
for (int coin : coins) {
for (int a = coin; a <= amount; a++) {
dp[a] += dp[a - coin];
}
}
return dp[amount];
}
};
More Dynamic Programming problems
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)