From 12b62a4e1ced243fd66fcda289ded88f99fd032f Mon Sep 17 00:00:00 2001 From: zhangzw Date: Tue, 8 Jun 2021 17:07:06 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00322.=E9=9B=B6=E9=92=B1?= =?UTF-8?q?=E5=85=91=E6=8D=A2=20Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0322.零钱兑换.md | 61 +++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/problems/0322.零钱兑换.md b/problems/0322.零钱兑换.md index ddcd739b..2c9ff8cf 100644 --- a/problems/0322.零钱兑换.md +++ b/problems/0322.零钱兑换.md @@ -211,7 +211,68 @@ Python: Go: +```go +// 版本一, 先遍历物品,再遍历背包 +func coinChange1(coins []int, amount int) int { + dp := make([]int, amount+1) + // 初始化dp[0] + dp[0] = 0 + // 初始化为math.MaxInt32 + for j := 1; j <= amount; j++ { + dp[j] = math.MaxInt32 + } + // 遍历物品 + for i := 0; i < len(coins); i++ { + // 遍历背包 + for j := coins[i]; j <= amount; j++ { + //if dp[j-coins[i]] != math.MaxInt32 { + // 推导公式 + dp[j] = min(dp[j], dp[j-coins[i]]+1) + fmt.Println(dp,j,i) + //} + } + } + // 没找到能装满背包的, 就返回-1 + if dp[amount] == math.MaxInt32 { + return -1 + } + return dp[amount] +} + +// 版本二,先遍历背包,再遍历物品 +func coinChange2(coins []int, amount int) int { + dp := make([]int, amount+1) + // 初始化dp[0] + dp[0] = 0 + // 遍历背包,从1开始 + for j := 1; j <= amount; j++ { + // 初始化为math.MaxInt32 + dp[j] = math.MaxInt32 + // 遍历物品 + for i := 0; i < len(coins); i++ { + if j >= coins[i] && dp[j-coins[i]] != math.MaxInt32 { + // 推导公式 + dp[j] = min(dp[j], dp[j-coins[i]]+1) + //fmt.Println(dp) + } + } + } + // 没找到能装满背包的, 就返回-1 + if dp[amount] == math.MaxInt32 { + return -1 + } + return dp[amount] +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} + +```