w = [6,3,5,4,6] # 物品价值
v = [2,2,6,5,4] # 物品体积
def KnapSack(w,v,c):
n = len(w) # 物品个数
W = w[:] # 克隆数组,并在0位置插入0,保证元素索引从1开始
V = v[:]
W.insert(0,0)
V.insert(0,0)
arr = [[0] * (c + 1) for i in range(n + 1)] # 动态规划数组
print('动态规划数组如下:')
for i in range(1,n + 1):
for j in range(1,c + 1):
arr[i][j] = arr[i-1][j]
if j >= V[i] and arr[i][j] < arr[i-1][j-V[i]] + W[i]: # 判断此物品加入背包是否对子问题最优解有影响
arr[i][j] = arr[i-1][j-V[i]] + W[i]
print('{:2d}'.format(arr[i][j]),end = ' ')
print()
rest = c
print('最优解为:')
for i in range(n,0,-1):
if arr[i][rest] == arr[i-1][rest]: # 此物品不在背包内
continue
else:
print(i,end = ' ') # 此物品在背包内,将此物品拿出
rest -= V[i]
print()
return arr[n][c]
print('最优值为:',KnapSack(w,v,10))
输出:
动态规划数组如下:
0 6 6 6 6 6 6 6 6 6
0 6 6 9 9 9 9 9 9 9
0 6 6 9 9 9 9 11 11 14
0 6 6 9 9 9 10 11 13 14
0 6 6 9 9 12 12 15 15 15
最优解为:
5 2 1
最优值为: 15