Update 背包理论基础01背包-1.md

This commit is contained in:
jianghongcheng
2023-06-03 20:10:36 -05:00
committed by GitHub
parent 3c9419a8e4
commit 09ab0e4873

View File

@ -339,38 +339,63 @@ public class BagProblem {
``` ```
### python ### python
无参数版
```python ```python
def test_2_wei_bag_problem1(bag_size, weight, value) -> int: def test_2_wei_bag_problem1():
rows, cols = len(weight), bag_size + 1 weight = [1, 3, 4]
dp = [[0 for _ in range(cols)] for _ in range(rows)] value = [15, 20, 30]
bagweight = 4
# 初始化dp数组. # 二维数组
for i in range(rows): dp = [[0] * (bagweight + 1) for _ in range(len(weight))]
dp[i][0] = 0
first_item_weight, first_item_value = weight[0], value[0]
for j in range(1, cols):
if first_item_weight <= j:
dp[0][j] = first_item_value
# 更新dp数组: 先遍历物品, 再遍历背包. # 初始化
for i in range(1, len(weight)): for j in range(weight[0], bagweight + 1):
cur_weight, cur_val = weight[i], value[i] dp[0][j] = value[0]
for j in range(1, cols):
if cur_weight > j: # 说明背包装不下当前物品.
dp[i][j] = dp[i - 1][j] # 所以不装当前物品.
else:
# 定义dp数组: dp[i][j] 前i个物品里放进容量为j的背包价值总和最大是多少。
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - cur_weight]+ cur_val)
print(dp) # weight数组的大小就是物品个数
for i in range(1, len(weight)): # 遍历物品
for j in range(bagweight + 1): # 遍历背包容量
if j < weight[i]:
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i])
print(dp[len(weight) - 1][bagweight])
test_2_wei_bag_problem1()
```
有参数版
```python
def test_2_wei_bag_problem1(weight, value, bagweight):
# 二维数组
dp = [[0] * (bagweight + 1) for _ in range(len(weight))]
# 初始化
for j in range(weight[0], bagweight + 1):
dp[0][j] = value[0]
# weight数组的大小就是物品个数
for i in range(1, len(weight)): # 遍历物品
for j in range(bagweight + 1): # 遍历背包容量
if j < weight[i]:
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i])
return dp[len(weight) - 1][bagweight]
if __name__ == "__main__": if __name__ == "__main__":
bag_size = 4
weight = [1, 3, 4] weight = [1, 3, 4]
value = [15, 20, 30] value = [15, 20, 30]
test_2_wei_bag_problem1(bag_size, weight, value) bagweight = 4
result = test_2_wei_bag_problem1(weight, value, bagweight)
print(result)
``` ```