栈应用之 背包问题(Python 版)

栈应用之 背包问题

背包问题描述:一个背包里可以放入重量为weight的物品,现有n件物品的集合s,其中物品的重量为别为w0,w1,...,wn-1。问题是能否从中选出若干件物品,其重量之和正好等于weight,如果存在就说明这一背包问题有解,否则就无解。

 

  • 使用递归方式求解 
 1 def knap_rec(weight,wlist,n) :
 2     if weight == 0 :
 3         return True
 4     if weight < 0 or (weight >0 and n < 1) :
 5         return False 
 6     if knap_rec(weight - wlist[n-1],wlist,n-1) :
 7         print("Item" + str(n) + ":" , wlist[n-1])
 8         return True
 9     if knap_rec(weight,wlist,n-1) :
10         return True
11     else :
12         return False

 

 

  • 使用栈定义非递归方式求解、

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/zlsgh/p/9580230.html