我试图用非整数值减少Knapsack DP算法所需的时间和空间。
http://en.wikipedia.org/wiki/Knapsack_problem#Meet-in-the-Middle_Algorithm
In particular, if the [elements] are nonnegative but not integers, we could
still use the dynamic programming algorithm by scaling and rounding (i.e. using
fixed-point arithmetic), but if the problem requires fractional digits of
precision to arrive at the correct answer, W will need to be scaled by 10^d,
and the DP algorithm will require O(W * 10^d) space and O(nW * 10^d) time.
DP背包算法使用[n x W]矩阵,用结果填充它,但有些列永远不会被填充 - 它们不匹配任何对象权重的组合。这样,它们最终会在每一行中填充零,只会浪费时间和空间。
如果我们使用哈希数组而不是矩阵,我们可以减少所需的时间和空间。
edit:
knapsack capacity = 2
items: [{weight:2,value:3} ]
[0 1 2]
[0 0 0]
2: [0 0 3]
^
Do we need this column?
Substitution with hash:
2: {0:0, 2:3}
在Python中,dict插入有一个O(n)更坏的情况和一个O(1)"摊销"线性时间。
我错过了什么吗?
背包DP算法的这种变化的复杂性是什么?
答案 0 :(得分:0)
你所说的是,如果我可以这么说的话,那些快乐的案例 - 你的物品数量非常少,可以插入量大的背包中。在这种情况下,hashmap可以证明是优化,触发从O(W * n)
到O(min(O(2^n * n), O(W * n)))
的复杂性(2^n
是n个元素的组合数)。然而,通过这种估计,很明显,对于不是那么多的元素,O(2^n * n)
将支配其他估计。另请注意,虽然O(W * n)
属于同一类,但后一种情况下的常数要大得多(甚至更多:第二种情况下的估计考虑了摊销的复杂性,而不是最坏的情况)。
因此,在某些情况下,您可以证明哈希映射更好,但在通常情况下,反之亦然。