From 6a42937927f1e9c9c4925fa53332ddf4fe275d24 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Sat, 12 Jun 2021 14:29:59 -0400 Subject: [PATCH] =?UTF-8?q?Update=20=E8=83=8C=E5=8C=85=E7=90=86=E8=AE=BA?= =?UTF-8?q?=E5=9F=BA=E7=A1=8001=E8=83=8C=E5=8C=85-2.md=20Python=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加python部分代码. 测试结果: ``` [[0, 15, 15, 15, 15], [0, 15, 15, 20, 35], [0, 15, 15, 20, 35]] ``` 与题解一致. --- problems/背包理论基础01背包-1.md | 35 ++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md index 36544256..1269d9c1 100644 --- a/problems/背包理论基础01背包-1.md +++ b/problems/背包理论基础01背包-1.md @@ -307,6 +307,41 @@ Java: Python: +```python +def test_2_wei_bag_problem1(bag_size, weight, value) -> int: + rows, cols = len(weight), bag_size + 1 + dp = [[0 for _ in range(cols)] for _ in range(rows)] + res = 0 + + # 初始化dp数组. + for i in range(rows): + 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)): + cur_weight, cur_val = weight[i], value[i] + 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) + if dp[i][j] > res: + res = dp[i][j] + + print(dp) + + +if __name__ == "__main__": + bag_size = 4 + weight = [1, 3, 4] + value = [15, 20, 30] + test_2_wei_bag_problem1(bag_size, weight, value) +``` Go: