题目:46. 携带研究材料
我的感悟:
- 一维是二维的压缩
理解难点:
- 倒序遍历j
- 因为每轮的数字是由左上决定的。
- 遍历的时候,从右侧遍历,是不会影响左侧的。
听课笔记:
代码示例:
def bag_problem(weight, value, bagWeight):
# 初始化
dp = [0] * (bagWeight + 1)
for i in range(len(weight)): # 遍历物品
for j in range(bagWeight, weight[i] - 1, -1): # 遍历背包容量
dp[j] = max(dp[j], dp[j - weight[i]] + value[i])
return dp[bagWeight]
m, n = map(int, input().split())
weight = list(map(int, input().split()))
value = list(map(int, input().split()))
res = bag_problem(weight, value, n)
print(res)
通过截图:
扩展写法:
网友评论:
资料:
01背包问题 一维
视频讲解:https://www.bilibili.com/video/BV1BU4y177kY
标签:遍历,weight,8C%,46,随想录,value,bagWeight,part4,dp From: https://www.cnblogs.com/liqi175/p/18035089