背包问题解析
python实现:
#0-1背包问题
'''
四样物体(things):wight:[2,3,4,5]
value:[3,4,5,6]
bag capacity:8
填表:
things/bag capacity 0, 1 2 3 4 5 6 7 8
0 0, 0, 0, 0, 0, 0, 0, 0, 0
1 0, 0, 3, 3, 3, 3, 3, 3, 3
2 0, 0, 3, 4, 4, 7, 7, 7, 7
3 0, 0, 3, 4, 5, 7, 8, 9, 9
4 0, 0, 3, 4, 5, 7, 8, 9, 10
'''
import numpy as np
def dpbag(weight, value, capacity):
#创建二维数组保存
results = np.zeros((len(weight) + 1 , capacity + 1), dtype = int)
#第0行的每一个赋0
results[0, :] = 0
#第0列的每一个赋0
results[:, 0] = 0
for i in range(1, len(weight) + 1):
for j in range(1, capacity + 1):
#如果该数比num要大,则此时需要考虑上一个数
if weight[i-1] > j:
results[i, j] = results[i-1, j]
else:
#不选weight[i - 1]
A = results[i - 1,j]
#选择weight[i - 1]
B = results[i - 1, j - weight[i - 1]] + value[i - 1]
#取AB中最大值
results[i, j] = max(A , B)
return results[-1, -1]
dpbag([2,3,4,5],[3,4,5,6],8)