0-1背包python实现:
maxW = -1 # tracking the max weight
def backpack(i, cw, items, w):
'''
# i: the ith item, integer
# cw: current weight, integer
# items: python list of item weights
# w: upper limit weight the backpack can load
'''
global maxW
if cw==w or i==len(items): # base case
if cw > maxW:
maxW = cw
return
# There are 2 states, traverse both!!!
backpack(i+1, cw, items, w) # do not choose
if (cw + items[i] <= w):
backpack(i+1, cw+items[i], items, w) # choose
# how to use
items = [2, 2, 4, 6, 3]
backpack(0, 0, items, 10)
print(maxW)
展开