SDE & MLE Prep

518. Coin Change II

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]