From 7fe87c16d93eb2b2fdaeaf0cc53a1499135d0e3a Mon Sep 17 00:00:00 2001 From: zhangzw Date: Mon, 7 Jun 2021 12:03:53 +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-2=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背包-2.md | 29 ++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/背包理论基础01背包-2.md b/problems/背包理论基础01背包-2.md index e831d88f..1d3f8b03 100644 --- a/problems/背包理论基础01背包-2.md +++ b/problems/背包理论基础01背包-2.md @@ -219,7 +219,36 @@ Python: Go: +```go +func test_1_wei_bag_problem(weight, value []int, bagWeight int) int { + // 定义 and 初始化 + dp := make([]int,bagWeight+1) + // 递推顺序 + for i := 0 ;i < len(weight) ; i++ { + // 这里必须倒序,区别二维,因为二维dp保存了i的状态 + for j:= bagWeight; j >= weight[i] ; j-- { + // 递推公式 + dp[j] = max(dp[j], dp[j-weight[i]]+value[i]) + } + } + //fmt.Println(dp) + return dp[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_1_wei_bag_problem(weight,value,4) +} +```