【问题标题】:How to get the list of selected items in naive 0-1 knapsack?如何获取天真的0-1背包中的选定项目列表?
【发布时间】: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


【解决方案1】:

所以这里的技巧是通过选择该路径返回所选项目的路径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, wt, val, n-1)
 
    # return the maximum of two cases:
    # (1) nth item included
    v1, p1 = knapSack(W-wt[n-1], wt, val, n-1)
    v1 += val[n-1]
    p1 = [items[n-1]] + p1
    
    # (2) not included
    v2, p2 = knapSack(W, wt, val, 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, wt, val, n)
    print(val, path)

请注意,您可以使用一些额外的措施来加速此代码。最值得注意的是添加记忆,然后将其转换为自下而上的 dp 解决方案。如果您想了解有关如何应用这些的更多信息,请随时发表评论。

【讨论】:

    猜你喜欢
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 2015-01-23
    • 2017-09-10
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多