518. Coin Change II
Asked at 12Google38Amazon37Microsoft33Bloomberg25Meta24Apple22Mastercard94Infosys45PornHub87DE Shaw38TikTok35Salesforce28
Problem
Count the combinations of coins from coins (unlimited of each) that add up to amount. Order doesn't matter: 1 + 2 and 2 + 1 are the same combination.
Example: amount = 5, coins = [1,2,5] → 4; amount = 3, coins = [2] → 0
Constraints: the answer fits in 32 bits.
Count combinations (order doesn't matter) → outer loop over coins, inner over amounts: dp[a] += dp[a − coin]. Each coin is "introduced" once, so orderings aren't double-counted.
Complexity: O(amount × coins).
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
dp = [1] + [0] * amount
for c in coins:
for a in range(c, amount + 1):
dp[a] += dp[a - c]
return dp[amount]
assert Solution().change(5, [1, 2, 5]) == 4
assert Solution().change(3, [2]) == 0
assert Solution().change(10, [10]) == 1
class Solution {
public int change(int amount, int[] coins) {
int[] dp = new int[amount + 1];
dp[0] = 1;
for (int c : coins)
for (int a = c; a <= amount; a++) dp[a] += dp[a - c];
return dp[amount];
}
}
func change(amount int, coins []int) int {
dp := make([]int, amount+1) // dp[a] = combinations summing to a
dp[0] = 1
for _, c := range coins { // coins in the outer loop: each combination counted once
for a := c; a <= amount; a++ {
dp[a] += dp[a-c]
}
}
return dp[amount]
}