def knapsack_dynamic(ws, vs, W):
n = len(ws)
K = [[0] * (W+1)] * (n+1)
for i in range(n+1):
for w in range(W+1):
if i == 0 or w == 0: # knapsack is empty or no more weight to carry
K[i][w] = 0
else:
if ws[i-1] > w:
K[i][w] = K[i-1][w]
else:
K[i][w] = max(vs[i-1] + K[i-1][w-ws[i-1]], K[i-1][w])
return K[n][W]
下面是测试方法:
maxw = 50
ws = [10, 20, 30]
vs = [60, 100, 120]
print(knapsack_dynamic(ws, vs, maxw)) # should print 220