Update 背包问题理论基础完全背包.md

添加 python3 版本代码
This commit is contained in:
haofeng
2021-06-06 15:55:35 +08:00
parent b960ff0f40
commit 9c0fe0ff49

View File

@ -179,9 +179,45 @@ int main() {
Java
Python
```python3
# 先遍历物品,再遍历背包
def test_complete_pack1():
weight = [1, 3, 4]
value = [15, 20, 30]
bag_weight = 4
dp = [0]*(bag_weight + 1)
for i in range(len(weight)):
for j in range(weight[i], bag_weight + 1):
dp[j] = max(dp[j], dp[j - weight[i]] + value[i])
print(dp[bag_weight])
# 先遍历背包,再遍历物品
def test_complete_pack2():
weight = [1, 3, 4]
value = [15, 20, 30]
bag_weight = 4
dp = [0]*(bag_weight + 1)
for j in range(bag_weight + 1):
for i in range(len(weight)):
if j >= weight[i]: dp[j] = max(dp[j], dp[j - weight[i]] + value[i])
print(dp[bag_weight])
if __name__ == '__main__':
test_complete_pack1()
test_complete_pack2()
```
Go