package main import "fmt" func coinChangeWays(coins []int, amount int) int { dp := make([]int, amount+1) dp[0] = 1 for _, coin := range coins { for i := coin; i <= amount; i++ { dp[i] += dp[i-coin] } } return dp[amount] } func main() { coins := []int{1, 2, 3} amount := 5 fmt.Println(coinChangeWays(coins, amount)) }
The code uses dynamic programming to count the number of ways to make change. For amount 5 and coins [1, 2, 3], the total ways are 7.
package main import "fmt" func coinChangeWays(coins []int, amount int) int { dp := make([]int, amount+1) dp[0] = 1 for _, coin := range coins { for i := coin; i <= amount; i++ { dp[i] += dp[i-coin] } } return dp[amount] } func main() { coins := []int{2, 5, 3, 6} amount := 4 fmt.Println(coinChangeWays(coins, amount)) }
The ways to make 4 are using two 2-coin pieces or one 3-coin plus one 1-coin (but 1 is not in coins), so only two 2-coin pieces and one 3-coin plus one 1-coin is invalid. Actually, only two 2-coin pieces and one 3-coin plus one 1-coin is invalid. So total ways is 1.
package main import "fmt" func coinChangeWays(coins []int, amount int) int { dp := make([]int, amount) dp[0] = 1 for _, coin := range coins { for i := coin; i <= amount; i++ { dp[i] += dp[i-coin] } } return dp[amount] } func main() { coins := []int{1, 2} amount := 3 fmt.Println(coinChangeWays(coins, amount)) }
The dp slice is created with length amount (3), but indices go up to amount (3), which is out of range since indexing is 0-based.
package main import "fmt" func coinChangeWays(coins []int, amount int) int { dp := make([]int, amount+1) dp[0] = 1 for _, coin := range coins { for i := coin; i <= amount; i++ { dp[i] += dp[i-coin] } } return dp[amount] } func main() { coins := []int{1, 2, 3} amount := 0 fmt.Println(coinChangeWays(coins, amount)) }
There is exactly one way to make amount zero: use no coins.
Iterating coins first ensures combinations are counted without duplicates because each coin is considered in sequence, preventing counting the same combination multiple times in different orders.
