From 09ab0e48738d17c184c197d5043a2e8423d0686d Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 3 Jun 2023 20:10:36 -0500 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-1.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/背包理论基础01背包-1.md | 75 ++++++++++++++++-------- 1 file changed, 50 insertions(+), 25 deletions(-) diff --git a/problems/背包理论基础01背包-1.md b/problems/背包理论基础01背包-1.md index c2525248..9df2fc4c 100644 --- a/problems/背包理论基础01背包-1.md +++ b/problems/背包理论基础01背包-1.md @@ -339,38 +339,63 @@ public class BagProblem { ``` ### 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)] +def test_2_wei_bag_problem1(): + weight = [1, 3, 4] + value = [15, 20, 30] + bagweight = 4 - # 初始化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 = [[0] * (bagweight + 1) for _ in range(len(weight))] - # 更新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) + # 初始化 + for j in range(weight[0], bagweight + 1): + dp[0][j] = value[0] - 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__": - bag_size = 4 - weight = [1, 3, 4] - value = [15, 20, 30] - test_2_wei_bag_problem1(bag_size, weight, value) + + weight = [1, 3, 4] + value = [15, 20, 30] + bagweight = 4 + + result = test_2_wei_bag_problem1(weight, value, bagweight) + print(result) + + ```