这是我从麻省理工学院公开课程中学习的一个简单的背包问题,我从这里学习。
该脚本针对权重和值进行了优化,但我希望它能够优化,因此没有类重复。因此,例如,如果我的上限为 10,它将返回w[0] v[0] c[0] and w[2] v[2] c[2]
而不是w[0] v[0] c[0] and w[1] v[1] c[1] and w[2] v[2] c[2]
weight= [5,3,2]
value = [9,7,8]
the_class = ["A","C","C"]
cap = 5
'''
w = the weight of item
v = the value of item
i = index of the item
aW = availible weight left (cap - w[i])
c = class of item
'''
def maxVal(w, v, i, aW,c):
if i == 0:
if w[i] <= aW:
return v[i]
else:
return 0
without_i = maxVal(w, v, i-1, aW, c)
if w[i] > aW:
return without_i
else:
with_i = v[i] + maxVal(w, v, i-1, aW - w[i], c)
return max(with_i, without_i)
res = maxVal(weight,value, len(value)-1, cap, the_class)
print "The result: ",res