day42 动态规划part4 代码随想录算法训练营 卡尔网46. 携带研究材料
题目:卡尔网-46. 携带研究材料
我的感悟:
- 有1个测试用例没通过。
- 还要多练习
- =====我知道哪里错了======
- 是>=号的问题
理解难点:
- dp递推公式的由来,
- 初始化的参数。
听课笔记:
代码示例:
def bag_problem(weight, value, bagweight):
# [1,3,4] [15,20,30] 4
if bagweight == 1:
index = weight.index(1)
return value[index]
# 二维数组
j_hang = bagweight + 1 # 5
i_lie = len(weight) # 3列
dp = [[0] * (j_hang) for _ in range(i_lie)]
# 初始化
for j in range(weight[0], j_hang):
dp[0][j] = value[0]
# 遍历物品和容量
for i in range(1, i_lie): # 外层 # 第0行已经初始化了
for j in range(j_hang): # 内层
# 拿
if j - weight[i] > 0:
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i])
# 不拿
else:
dp[i][j] = dp[i - 1][j]
return dp[i_lie - 1][j_hang - 1]
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)
错误的截图:
修改后的截图:
看评论区可以通过的写法:
def fun():
n, weight, vals = [int(x) for x in input().split()], [int(x) for x in input().split()], [int(x) for x in input().split()]
nums, bag = n[0], n[1]
dp = [[0] * (bag+1) for _ in range(nums)]
for i in range(nums):
dp[i][0] = 0
# for j in range(bag+1):
# if weight[0] > j:
# dp[0][j] = 0
# else:
# dp[0][j] = vals[0]
# 初始化
for j in range(weight[0], bag+1):
dp[0][j] = vals[0]
for i in range(1, nums):
for j in range(1, bag+1):
dp[i][j] = dp[i-1][j]
if j >= weight[i]:
dp[i][j] = max(dp[i][j], dp[i-1][j-weight[i]] + vals[i])
return dp[nums-1][bag]
if __name__ == '__main__':
print(fun())
资料:
01背包问题 二维