mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
增加 背包理论基础01背包-2.md Python3 实现代码
This commit is contained in:
@ -242,7 +242,24 @@ Java:
|
||||
|
||||
|
||||
Python:
|
||||
```python
|
||||
def test_1_wei_bag_problem():
|
||||
weight = [1, 3, 4]
|
||||
value = [15, 20, 30]
|
||||
bag_weight = 4
|
||||
# 初始化: 全为0
|
||||
dp = [0] * (bag_weight + 1)
|
||||
|
||||
# 先遍历物品, 再遍历背包容量
|
||||
for i in range(len(weight)):
|
||||
for j in range(bag_weight, weight[i] - 1, -1):
|
||||
# 递归公式
|
||||
dp[j] = max(dp[j], dp[j - weight[i]] + value[i])
|
||||
|
||||
print(dp)
|
||||
|
||||
test_1_wei_bag_problem()
|
||||
```
|
||||
|
||||
Go:
|
||||
```go
|
||||
|
Reference in New Issue
Block a user