这是我第一次处理动态编程的任务,我觉得很难。
问题:
考虑到容量为W和n金条的重量[wt [0],...,wt [n - 1])的背包,找到可以装入背包而不重复的最大金条数。
输入: 第1行:(容量背包(W))(num金条(n)) 第2行:n个金条的重量(wt)
输出:最大重量(金条),适合容量W
的背包我的代码:
import sys
def optimal_weight(W, wt):
"""Find max weight that can fit in knapsack size W."""
# Create n nested arrays of 0 * (W + 1)
max_vals = [[0] * (W + 1) for x in range(len(wt))]
# Set max_vals[0] to wt[0] if wt[0] <= j
max_vals[0] = [wt[0] if wt[0] <= j else 0 for j in range(W + 1)]
for i in range(1, len(wt)):
for j in range(1, W + 1):
value = max_vals[i - 1][j] # previous i @ same j
if wt[i] <= j:
val = (max_vals[i - 1][j - wt[i]]) + wt[i]
if value < val:
value = val
max_vals[i][j] = value
else:
max_vals[i][j] = value
return max_vals[-1][-1]
if __name__ == '__main__':
input = sys.stdin.read()
W, n, *wt = list(map(int, input.split()))
print(optimal_weight(W, wt))
我出错的任何想法?当我观察到我的结束max_vals时,我发现max_vals,因为我增加,只是在每个嵌套列表中替换越来越小的值(i - 1)。换句话说,当我继续迭代时,更少的0被替换为max_vals [i - 1] [j]的值。有点尴尬的是,我已经在这方面工作了将近一个星期而无法解决这个问题。除课堂讲座视频外,This video一直是我的主要参考点。动态编程被证明是一个相当大的挑战。
答案 0 :(得分:3)
轻松修复。无法相信我错过了它。只是弄乱了else语句。需要额外的。
if value < val:
value = val
max_vals[i][j] = value
else:
max_vals[i][j] = value # set to [i - 1][j]
else:
max_vals[i][j] = value # set to [i - 1][j]