From 0913f488a401d5102a347852e1eecd3b30836f1f Mon Sep 17 00:00:00 2001 From: zhangzw Date: Mon, 7 Jun 2021 12:03:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=83=8C=E5=8C=85=E7=90=86?= =?UTF-8?q?=E8=AE=BA=E5=9F=BA=E7=A1=8001=E8=83=8C=E5=8C=85-1=20Go=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/背包理论基础01背包-1.md | 33 ++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md index a78d9232..de4508ad 100644 --- a/problems/背包理论基础01背包-1.md +++ b/problems/背包理论基础01背包-1.md @@ -273,7 +273,40 @@ Python: Go: +```go +func test_2_wei_bag_problem1(weight, value []int, bagWeight int) int { + // 定义dp数组 + dp := make([][]int, len(weight)) + for i, _ := range dp { + dp[i] = make([]int, bagWeight+1) + } + // 初始化 + for j := bagWeight; j >= weight[0]; j-- { + dp[0][j] = dp[0][j-weight[0]] + value[0] + } + // 递推公式 + for i := 1; i < len(weight); i++ { + //正序,也可以倒序 + for j := weight[i];j<= bagWeight ; j++ { + dp[i][j] = max(dp[i-1][j], dp[i-1][j-weight[i]]+value[i]) + } + } + return dp[len(weight)-1][bagWeight] +} +func max(a,b int) int { + if a > b { + return a + } + return b +} + +func main() { + weight := []int{1,3,4} + value := []int{15,20,30} + test_2_wei_bag_problem1(weight,value,4) +} +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)