假设你是一个小偷并且你入侵了一所房子。你在里面找到了以下物品:
花瓶重3磅,价值50美元 重量为6磅,价值30美元的银块 一幅重4磅,价值40美元的画作 重量为5磅,价值10美元的镜子。
解决这个10磅大小的背包问题是90美元。
动态编程制作的表格是: -
现在我想知道我使用这张表放入口袋中的哪些元素然后如何回溯?
答案 0 :(得分:7)
从您的DP表我们知道f [i] [w] =总重量小于或等于w的项目1..i子集的最大总值。
我们可以使用表格本身来恢复最佳包装:
def reconstruct(i, w): # reconstruct subset of items 1..i with weight <= w
# and value f[i][w]
if i == 0:
# base case
return {}
if f[i][w] > f[i-1][w]:
# we have to take item i
return {i} UNION reconstruct(i-1, w - weight_of_item(i))
else:
# we don't need item i
return reconstruct(i-1, w)
答案 1 :(得分:0)
使用循环:
for (int n = N, w = W; n > 0; n--)
{
if (sol[n][w] != 0)
{
selected[n] = 1;
w = w - wt[n];
}
else
selected[n] = 0;
}
System.out.print("\nItems with weight ");
for (int i = 1; i < N + 1; i++)
if (selected[i] == 1)
System.out.print(val[i] +" ");
答案 2 :(得分:0)
我有一个受@NiklasB启发的迭代算法。当递归算法遇到某种递归限制时,它会起作用。
def reconstruct(i, w, kp_soln, weight_of_item):
"""
Reconstruct subset of items i with weights w. The two inputs
i and w are taken at the point of optimality in the knapsack soln
In this case I just assume that i is some number from a range
0,1,2,...n
"""
recon = set()
# assuming our kp soln converged, we stopped at the ith item, so
# start here and work our way backwards through all the items in
# the list of kp solns. If an item was deemed optimal by kp, then
# put it in our bag, otherwise skip it.
for j in range(0, i+1)[::-1]:
cur_val = kp_soln[j][w]
prev_val = kp_soln[j-1][w]
if cur_val > prev_val:
recon.add(j)
w = w - weight_of_item[j]
return recon