Coin Change II

Pattern: Subsequences and knapsack

medium

Count the combinations of coins (each usable many times) that make the amount. Put coins in the outer loop and amounts in the inner loop, so each combination is counted once, in coin order.

The problem

Return the number of combinations of coins that sum to amount, using each coin value any number of times. Order does not matter.

Think first

  • Is 1 + 2 different from 2 + 1 here?
  • How does the loop order decide that?
  • Which direction does the inner loop go?

Hints

    Brute force, and why it fails

    Generate every combination: exponential.

    The key insight

    Adding coin types one at a time counts each multiset exactly once.

    Dry run

    ways1 1 1 1 1 1

    amount 5, coins [1, 2, 5]. After coin 1: every amount has 1 way.

    Step 1 of 2

    The plan

    ways = [1, 0, ...]
    for c in coins: for a from c up to amount: ways[a] += ways[a - c]
    

    Complexity

    Time
    O(amount × coins)
    Space
    O(amount)

    One table.

    Edge cases

    • Amount 0: 1.
    • No combination: 0.
    • Large counts.
    I've built my logic, show the code

    Java

    class Solution {
        public int change(int amount, int[] coins) {
            int[] ways = new int[amount + 1];       // ways[a]: combinations making a with the coins so far
            ways[0] = 1;
            for (int c : coins)                     // coins in the outer loop: each combination is counted once, in coin order
                for (int a = c; a <= amount; a++) ways[a] += ways[a - c];   // upwards: c may be used again
            return ways[amount];
        }
    }

    C++

    class Solution {
    public:
        int change(int amount, vector<int>& coins) {
            vector<unsigned long long> ways(amount + 1, 0);   // ways[a]: combinations making a with the coins so far
            ways[0] = 1;
            for (int c : coins)                     // coins in the outer loop: each combination is counted once, in coin order
                for (int a = c; a <= amount; a++) ways[a] += ways[a - c];   // upwards: c may be used again
            return static_cast<int>(ways[amount]);
        }
    };

    Python

    class Solution:
        def change(self, amount: int, coins: list[int]) -> int:
            ways = [1] + [0] * amount               # ways[a]: combinations making a with the coins so far
            for c in coins:                         # coins in the outer loop: each combination counted once
                for a in range(c, amount + 1):      # upwards: c may be used again
                    ways[a] += ways[a - c]
            return ways[amount]

    Common mistakes

    • Amounts outside, which counts orders.
    • Looping downwards, which uses each coin once.

    Similar problems