給定不同面額的硬幣 coins 和一個總金額 amount。編寫一個函數來計算可以湊成總金額所需的最少的硬幣個數。如果沒有任何一種硬幣組合能組成總金額,返回 -1。
示例 1:
輸入: coins = [1, 2, 5], amount = 11
輸出: 3
解釋: 11 = 5 + 5 + 1
示例 2:
輸入: coins = [2], amount = 3
輸出: -1
說明:
你可以認為每種硬幣的數量是無限的。
方法:
- 狀態定義: dp[i] 代表湊成i所需最少硬幣個數
- 狀態轉移方程: dp[i] = min(dp[i-c] + 1) c -> coins
func min(a, b int) int {
if a < b {
return a
}
return b
}
func coinChange(coins []int, amount int) int {
if coins == nil || len(coins) == 0 {
return -1
}
dp := make([]int, amount+1)
for i := 1; i <= amount; i++ {
dp[i] = amount + 1
for _, c := range coins {
if i >= c {
dp[i] = min(dp[i], dp[i-c]+1)
}
}
}
if dp[amount] > amount {
return -1
}
return dp[amount]
}