LeetCode: 322. Coin Change
题目描述
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
Example 1:
Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
Note:
You may assume that you have an infinite number of each kind of coin.
解题思路 —— 动态规划
- 记:
dp[i]
为 钱数为 i
需要的最少硬币数 (-1 表示不可达) - 状态转移方程:
dp[i] = min{dp[i-coins[j]]+1}
,其中 j = 0...len(coins)
AC 代码
func min(lhv, rhv int) int {
switch {
case lhv == -1: return rhv
case rhv == -1: return lhv
case lhv < rhv: return lhv
default: return rhv
}
}
func coinChange(coins []int, amount int) int {
//dp[i]: amount 的钱需要的最少硬币数 (-1 表示不可达)
dp := []int {0}
for i := 1; i <= amount; i++ {
dp = append(dp, -1)
for j := 0; j < len(coins); j++ {
if i >= coins[j] && dp[i-coins[j]] != -1 {
dp[i] = min(dp[i], dp[i-coins[j]]+1)
}
}
}
return dp[amount]
}