我正在使用我在此链接Knapsack Problem
中找到的算法实现背包问题的片段我之前在Stack Overflow上问过这个问题,我在从程序的return语句中获取输出时遇到了问题。您可以在Previous question
查看我也在这里附上了算法的片段。
我为该算法编写了以下python代码段。这是:
def knapsack(v,w,n,W):
V = [[None for x in range(W+1)] for x in range(len(v)+1)]
keep = [[0 for x in range(W+1)] for x in range(len(v)+1)]
# print keep
for wy in range(W+1):
V[0][wy] = 0
for i in range(1,n+1):
for wx in range(W+1):
# print i,wx
if w[i-1] <= wx:
V[i][wx] = max(V[i-1][wx], v[i-1]+V[i-1][wx-w[i-1]])
keep[i][wx] = 1
else:
V[i][wx] = V[i-1][wx]
keep[i][wx] = 0
K = W
# print keep
for i in range(n,0,-1):
if keep[i][K] == 1:
print i
K = K - w[i-1]
return V[n][W]
print knapsack(v = [10,40,30,50], w=[5,4,6,3],n=4,W=10)
我应该以 4,2 作为我的价值,但获得 4,3 。请纠正我出错的地方。
答案 0 :(得分:0)
if语句中的问题:
if w[i-1] <= wx:
V[i][wx] = max(V[i-1][wx], v[i-1]+V[i-1][wx-w[i-1]])
keep[i][wx] = 1
else:
V[i][wx] = V[i-1][wx]
keep[i][wx] = 0
你正在做的(w[i-1] <= wx) and (v[i-1]+V[i-1][wx-w[i-1]] <= V[i-1][wx])
的
V[i][wx] = max(V[i-1][wx], v[i-1]+V[i-1][wx-w[i-1]])
keep[i][wx] = 1
但你应该
V[i][wx] = V[i-1][wx]
keep[i][wx] = 0