Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 518 Coin Change II - Combinations vs Permutations

The trap

Consider coins [1,2][1, 2] and amount 33. The combinations are: [1,1,1],[1,2][1,1,1], [1,2]. That's 22 ways. But if you count [1,2][1,2] and [2,1][2,1] separately, you get 33 ways. The naive approach: for each amount, try all coins.

This counts permutations because you might add coin 1, then coin 2, OR coin 2, then coin 1. The fix: for each coin, update all amounts. This keeps you process coins in a fixed order. Once you've "moved past" a coin, you never go back to it. That's what makes combinations work.