From 56306fc00b5fc111d66390f3d8c5bb0d25ffa166 Mon Sep 17 00:00:00 2001 From: wangq635 <643797037@qq.com> Date: Sat, 7 Sep 2024 19:50:44 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=20=E5=8A=A8=E6=80=81?= =?UTF-8?q?=E8=A7=84=E5=88=92=EF=BC=9A01=E8=83=8C=E5=8C=85=E7=90=86?= =?UTF-8?q?=E8=AE=BA=E5=9F=BA=E7=A1=80=EF=BC=88=E6=BB=9A=E5=8A=A8=E6=95=B0?= =?UTF-8?q?=E7=BB=84=EF=BC=89=E7=9A=84python=E7=89=88=E6=9C=AC=E7=9A=84?= =?UTF-8?q?=E6=BB=9A=E5=8A=A8=E6=95=B0=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/背包理论基础01背包-2.md | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/problems/背包理论基础01背包-2.md b/problems/背包理论基础01背包-2.md index cd8f317c..830958ef 100644 --- a/problems/背包理论基础01背包-2.md +++ b/problems/背包理论基础01背包-2.md @@ -294,23 +294,18 @@ public class Main { ```python n, bagweight = map(int, input().split()) - weight = list(map(int, input().split())) value = list(map(int, input().split())) -dp = [[0] * (bagweight + 1) for _ in range(n)] +dp = [0] * (bagweight + 1) # 创建一个动态规划数组dp,初始值为0 -for j in range(weight[0], bagweight + 1): - dp[0][j] = value[0] +dp[0] = 0 # 初始化dp[0] = 0,背包容量为0,价值最大为0 -for i in range(1, n): - 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]) +for i in range(n): # 应该先遍历物品,如果遍历背包容量放在上一层,那么每个dp[j]就只会放入一个物品 + for j in range(bagweight, weight[i]-1, -1): # 倒序遍历背包容量是为了保证物品i只被放入一次 + dp[j] = max(dp[j], dp[j - weight[i]] + value[i]) -print(dp[n - 1][bagweight]) +print(dp[bagweight]) ``` ### Go