In the 01 knapsack problem, when choosing whether to add an item to the backpack, the solution of the child problem must be compared with the solution of the problem that does not take the item, which causes many overlapping child problems, and uses the dynamic programming to solve. N=5 is the number of items, c=10 is the weight of the bag can bear, w=[2,2,6,5,4] is the weight of each item, v=[6,3,5,4,6] is the value of each item, first write the definition of recursion:
Then it is implemented from the bottom up, the code is as follows:
def bag (n,c,w,v):
res=[[-1 for J, Range (c+1)] for I in range (n+1) for
J in Range (c+1):
res[0][j]=0
for I in range (1,n+1): for
J in Range (1,c+1):
res[i][j]=res[i-1][j]
if j>=w[i-1] and res[i][j]<res[i-1][ J-W[I-1]]+V[I-1]:
res[i][j]=res[i-1][j-w[i-1]]+v[i-1] Return
res
def show (n,c,w,res):
print (' Maximum value: ', Res[n][c])
x=[false for I in range (n)]
j=c to
i in range (1,n+1):
if res[i][j]>res[i-1] [j]:
x[i-1]=true
j-=w[i-1]
print (' Selected items: ') for
I in range (n):
if x[i]:
print (' First ', I, ', ', end= ')
print (')
if __name__== ' __main__ ':
n=5
c=10 w=[2,2,6,5,4
]
v=[ 6,3,5,4,6]
res=bag (n,c,w,v) show
(n,c,w,res)
The output results are as follows:
Reprint Please specify: Transfer from http://blog.csdn.net/littlethunder/article/details/26575417