背包0-1路径重建(拿哪些物品)
我知道如何用动态规划方法解决背包 0-1 问题,但我很难弄清楚要拿哪些物品而不影响 O(N * C)(N 个物品,C 容量)的复杂性。
有什么想法(我更喜欢自下而上的方法)?
I know how to solve knapsack 0-1 problem with dynamic programming approach, but I am having troubles figuring out which items to take without compromising the complexity of O(N * C) (N items, C capacity).
Any ideas (I would prefer a bottom-up approach)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
假设,现在您将结果存储在数组
bool[] a
中,其中当i
可以达到总和时,a[i]
为 true .您将需要另一个数组
int[] b
,其中b[i]
是您放入背包中以求和i
的最后一个元素>。因此,在您拥有的地方,
您将需要
然后,找到可以采取哪些项目来实现 sum
i
是一个简单的循环。PS 为了简单起见,我使用两个数组,但显然数组
a
可以被删除。Suppose, right now you're storing results in array
bool[] a
, wherea[i]
is true when sumi
can be achieved.You'll need another array
int[] b
, whereb[i]
is a last element you've placed into knapsack to achieve sumi
.So, where you had
you'll need
Then, finding which items can be taken to achieve sum
i
is a simple loop.PS I use two arrays for simplicity, but obviously array
a
can be removed.这是在 O(n) 次重建路径的修改
Here is a modification to reconstruct path in O(n) times
检查附图中的 sol
Check the sol in the attached image
https://www. dropbox.com/s/ish7t5vgy91fovt/Screenshot%202017-01-01%2015.16.31.png?dl=0
打印调用者中的 tmpList,您将得到答案
https://www.dropbox.com/s/ish7t5vgy91fovt/Screenshot%202017-01-01%2015.16.31.png?dl=0
Print the tmpList in the caller and you will get the answer