我有这个python代码使用动态编程解决背包问题。 此函数返回最佳子集的总成本,但我希望它返回最佳子集的元素。任何人都可以帮我这个吗?
def knapSack(W, wt, val, n):
K = [[0 for x in range(W + 1)] for x in range(n + 1)]
# Build table K[][] in bottom up manner
for i in range(n + 1):
for w in range(W + 1):
if i == 0 or w == 0:
K[i][w] = 0
elif wt[i - 1] <= w:
K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1] [w])
else:
K[i][w] = K[i - 1][w]
return K[n][W]
val = [40, 100, 120,140]
wt = [1, 2, 3,4]
W = 4
n = len(val)
print(knapSack(W, wt, val, n))
答案 0 :(得分:1)
你能做的不是仅返回K [n] [W],而是返回K. 然后将K迭代为:
elements=list()
dp=K
w = W
i = n
while (i> 0):
if dp[w][i] - dp[w - wt(i)][i-1] == val(i):
#the element 'i' is in the knapsack
element.append(i)
i = i-1 //only in 0-1 knapsack
w -=wt(i)
else:
i = i-1
这个想法是你反向迭代K矩阵以确定哪些元素&#39;增加值以得到最佳K [W] [n]值。
答案 1 :(得分:0)
您可以将此代码添加到函数的末尾,以逐步完成添加的项:
res = K[n][W]
print(res)
w = W
for i in range(n, 0, -1):
if res <= 0:
break
if res == K[i - 1][w]:
continue
else:
print(wt[i - 1])
res = res - val[i - 1]
w = w - wt[i - 1]