01 Knapsack problem (Dynamic programming) Python implementation __python

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.