File tree Expand file tree Collapse file tree 1 file changed +6
-11
lines changed Expand file tree Collapse file tree 1 file changed +6
-11
lines changed Original file line number Diff line number Diff line change @@ -294,23 +294,18 @@ public class Main {
294294
295295``` python
296296n, bagweight = map (int , input ().split())
297-
298297weight = list (map (int , input ().split()))
299298value = list (map (int , input ().split()))
300299
301- dp = [[ 0 ] * (bagweight + 1 ) for _ in range (n)]
300+ dp = [0 ] * (bagweight + 1 ) # 创建一个动态规划数组dp,初始值为0
302301
303- for j in range (weight[0 ], bagweight + 1 ):
304- dp[0 ][j] = value[0 ]
302+ dp[0 ] = 0 # 初始化dp[0] = 0,背包容量为0,价值最大为0
305303
306- for i in range (1 , n):
307- for j in range (bagweight + 1 ):
308- if j < weight[i]:
309- dp[i][j] = dp[i - 1 ][j]
310- else :
311- dp[i][j] = max (dp[i - 1 ][j], dp[i - 1 ][j - weight[i]] + value[i])
304+ for i in range (n): # 应该先遍历物品,如果遍历背包容量放在上一层,那么每个dp[j]就只会放入一个物品
305+ for j in range (bagweight, weight[i]- 1 , - 1 ): # 倒序遍历背包容量是为了保证物品i只被放入一次
306+ dp[j] = max (dp[j], dp[j - weight[i]] + value[i])
312307
313- print (dp[n - 1 ][ bagweight])
308+ print (dp[bagweight])
314309
315310```
316311### Go
You can’t perform that action at this time.
0 commit comments