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