Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 518 Coin Change II - Walkthrough

Counting combinations

Trace Coin Change II with coins [1,2,5][1, 2, 5] and amount 55. The key is loop order: coins in outer loop to count combinations (not permutations). Let dp[a]dp[a] = number of ways to make amount aa. After coin 11: dp[1..5]=1dp[1..5] = 1 (only one way using just 1s). After coin 22: dp[2]=2dp[2]=2, dp[3]=2dp[3]=2, dp[4]=3dp[4]=3, dp[5]=3dp[5]=3. After coin 55: dp[5]=4dp[5]=4.

Answer: 44 ways. They are: [1,1,1,1,1][1,1,1,1,1], [1,1,1,2][1,1,1,2], [1,2,2][1,2,2], [5][5].