Dynamic Programming21 sections · 916 units
Open in Course

Challenge: Combinations vs Permutations

Understanding loop order

Swap the loop order: amount in outer loop, coins in inner loop. Now you count permutations instead of combinations. For amount 33 with coins [1,2][1, 2]: combinations are [1,1,1][1,1,1], [1,2][1,2] (22 ways).

Permutations are [1,1,1][1,1,1], [1,2][1,2], [2,1][2,1] (33 ways). Why does loop order matter? Coins-first keeps you never use a smaller coin after a larger one (avoiding [2,1][2,1] after counting [1,2][1,2]). Amount-first allows any order. Try both orders on coins [1,2,5][1, 2, 5] and amount 55. You should get 44 combinations but more permutations.