mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
添加背包理论基础01背包-2 Go版本
This commit is contained in:
@ -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)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user