Skip to content

Commit 09ab0e4

Browse files
Update 背包理论基础01背包-1.md
1 parent 3c9419a commit 09ab0e4

File tree

1 file changed

+52
-27
lines changed

1 file changed

+52
-27
lines changed

problems/背包理论基础01背包-1.md

+52-27
Original file line numberDiff line numberDiff line change
@@ -339,38 +339,63 @@ public class BagProblem {
339339
```
340340

341341
### python
342+
无参数版
343+
```python
344+
def test_2_wei_bag_problem1():
345+
weight = [1, 3, 4]
346+
value = [15, 20, 30]
347+
bagweight = 4
348+
349+
# 二维数组
350+
dp = [[0] * (bagweight + 1) for _ in range(len(weight))]
351+
352+
# 初始化
353+
for j in range(weight[0], bagweight + 1):
354+
dp[0][j] = value[0]
355+
356+
# weight数组的大小就是物品个数
357+
for i in range(1, len(weight)): # 遍历物品
358+
for j in range(bagweight + 1): # 遍历背包容量
359+
if j < weight[i]:
360+
dp[i][j] = dp[i - 1][j]
361+
else:
362+
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i])
342363

364+
print(dp[len(weight) - 1][bagweight])
365+
366+
test_2_wei_bag_problem1()
367+
368+
```
369+
有参数版
343370
```python
344-
def test_2_wei_bag_problem1(bag_size, weight, value) -> int:
345-
rows, cols = len(weight), bag_size + 1
346-
dp = [[0 for _ in range(cols)] for _ in range(rows)]
347-
348-
# 初始化dp数组.
349-
for i in range(rows):
350-
dp[i][0] = 0
351-
first_item_weight, first_item_value = weight[0], value[0]
352-
for j in range(1, cols):
353-
if first_item_weight <= j:
354-
dp[0][j] = first_item_value
355-
356-
# 更新dp数组: 先遍历物品, 再遍历背包.
357-
for i in range(1, len(weight)):
358-
cur_weight, cur_val = weight[i], value[i]
359-
for j in range(1, cols):
360-
if cur_weight > j: # 说明背包装不下当前物品.
361-
dp[i][j] = dp[i - 1][j] # 所以不装当前物品.
362-
else:
363-
# 定义dp数组: dp[i][j] 前i个物品里,放进容量为j的背包,价值总和最大是多少。
364-
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - cur_weight]+ cur_val)
365-
366-
print(dp)
371+
def test_2_wei_bag_problem1(weight, value, bagweight):
372+
# 二维数组
373+
dp = [[0] * (bagweight + 1) for _ in range(len(weight))]
367374

375+
# 初始化
376+
for j in range(weight[0], bagweight + 1):
377+
dp[0][j] = value[0]
378+
379+
# weight数组的大小就是物品个数
380+
for i in range(1, len(weight)): # 遍历物品
381+
for j in range(bagweight + 1): # 遍历背包容量
382+
if j < weight[i]:
383+
dp[i][j] = dp[i - 1][j]
384+
else:
385+
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i])
386+
387+
return dp[len(weight) - 1][bagweight]
368388

369389
if __name__ == "__main__":
370-
bag_size = 4
371-
weight = [1, 3, 4]
372-
value = [15, 20, 30]
373-
test_2_wei_bag_problem1(bag_size, weight, value)
390+
391+
weight = [1, 3, 4]
392+
value = [15, 20, 30]
393+
bagweight = 4
394+
395+
result = test_2_wei_bag_problem1(weight, value, bagweight)
396+
print(result)
397+
398+
374399
```
375400

376401

0 commit comments

Comments
 (0)