leetcode 322. 零钱兑换

题解

动态规划,dp[n] = min(dp[n], dp[n-v]+1),其中n代表总金额, v代表不同的硬币

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func coinChange(coins []int, amount int) int {
dp := make([]int, amount+1)
for n := 1; n <= amount; n++ {
for _, v := range coins {
if n >= v && dp[n-v] != -1 {
if dp[n] == 0 {
dp[n] = dp[n-v] + 1
} else if dp[n] > dp[n-v] + 1 {
dp[n] = dp[n-v] + 1
}
}
}
if dp[n] == 0 {
dp[n] = -1
}
}
return dp[amount]
}