如何解决如何获取天真的0-1背包中的选定项目列表?
我有一个背包问题的天真解决方案的代码,我想获取所选项目的列表,目前它正在返回所选项目的总和。任何帮助将不胜感激。蟒蛇代码:
def knapSack(W,wt,val,n):
# Base Case
if n == 0 or W == 0:
return 0
# If weight of the nth item is
# more than Knapsack of capacity W,# then this item cannot be included
# in the optimal solution
if (wt[n-1] > W):
return knapSack(W,n-1)
# return the maximum of two cases:
# (1) nth item included
# (2) not included
else:
return max(
val[n-1] + knapSack(
W-wt[n-1],n-1),knapSack(W,n-1))
# end of function knapSack
#Driver Code
items= [a,b,c,d,e]
val = [60,100,120,125,129]
wt = [10,20,30,40,50]
W = 70
n = len(val)
print knapSack(W,n)
解决方法
所以这里的技巧是通过选择该路径返回所选项目的路径 p
以及累积的值 v
。然后根据最大值 v
选择最佳路径。
def knapSack(W,wt,val,n):
# Base Case
if n == 0 or W == 0:
return 0,[]
# If weight of the nth item is
# more than Knapsack of capacity W,# then this item cannot be included
# in the optimal solution
if (wt[n-1] > W):
return knapSack(W,n-1)
# return the maximum of two cases:
# (1) nth item included
v1,p1 = knapSack(W-wt[n-1],n-1)
v1 += val[n-1]
p1 = [items[n-1]] + p1
# (2) not included
v2,p2 = knapSack(W,n-1)
return (v1,p1) if v1 >= v2 else (v2,p2)
if __name__ == "__main__":
items = list('abcde')
val = [60,100,120,125,129]
wt = [10,20,30,40,50]
W = 70
n = len(val)
val,path = knapSack(W,n)
print(val,path)
请注意,您可以使用一些其他措施来加速此代码。最值得注意的是添加记忆,然后将其转换为自下而上的 dp 解决方案。如果您想了解更多有关如何应用这些内容的信息,请随时发表评论。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。