In the 01 knapsack problem, choose whether to add an item to the backpack. It is necessary to compare the solution of the sub-problem of the item with the solution of the sub-problem of the item, which leads to a lot of overlapping sub-problems, which can be solved by using dynamic programming. N=5 is the number of items, c=10 is the weight of the bag can withstand, 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 the bottom-up is implemented with code such as the following:
def bag (n,c,w,v): Res=[[-1 for J in Range (c+1)] for I in range (n+1)]for J in Range (c+1): Res[0][j]=0for i in range (1,n+1): fo R 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 resdef Show (n,c,w,res):p rint (' Maximum value: ', Res[n][c]) X=[false for I in range (n)]j=cfor i in Range (1,n+1): If Res[i][j]>res[i-1][j]:x[i-1]=truej-=w[i-1]print (' Selected item: ') for I in Range (n): if X[i]:p rint (' first ', I, ' A, ', end= ') print (') if __name__== ' __main__ ': N=5c=10w=[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
01 Knapsack problem (Dynamic programming) Python implementation