【发布时间】:2021-04-13 22:23:42
【问题描述】:
我有一个背包问题的简单解决方案的代码,我想获取所选项目的列表,目前它正在返回所选项目的值的总和。任何帮助将不胜感激。 Python代码:
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, wt, val, 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], wt, val, n-1),
knapSack(W, wt, val, 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, wt, val, n)
【问题讨论】:
-
我只是按原样运行它,结果得到 285。你得到的是 534 吗?哦,没关系,对不起,我看不懂。我知道你在找什么。给我一秒钟,我会更新答案。
标签: python algorithm computer-science knapsack-problem