Box stacking:
You are given a set of boxes {b1, ..., bn}. Each box bj has an associated width wj ,height hj and depth dj . Give an algorithm for creating the highest possible stack of boxes with theconstraint that if box bj is stacked on box bi, the 2D base of bi must be larger in both dimensionsthan the base of bj . You can of course, rotate the boxes to decide which face is the base, but youcan use each box only once.For example, given two boxes with h1 = 5, w1 = 5, d1 = 1 and h2 = 4, w2 = 5, h2 = 2, you shouldorient box 1 so that it has a base of 5x5 and a height of 1 and stack box 2 on top of it oriented sothat it has a height of 5 for a total stack height of 6.
Solution:Recursion: Memoize over H(j, R), the tallest stack of boxes with j on top with rotation R.
H(j, R) = 0 if j = 0
H(j, R) = max{(H(i, R) + hj ) with i <j && wi>wj && di>dj } if j > 0
Running Time: The size of H is O(n|R|) where R is the number of possible rotations for a box.For our purposes, |R| = 3 (since we only care about which dimension we designate as the “height”)so |H| = O(n). Filling in each element of H is also O(n) for a total running time of O(n2).
这个分析在处理每个 box 只能使用一次的解法可能是不对的,因为放盒子的顺序被限制了即后面的盒子能放到前面的盒子上面,反之却是不行的。
下面的每个盒子可以被使用多次的解法,这个是无疑义的
即把每个盒子按照三种 rotation 的方法拆成三个盒子,排序后再使用类似上面的 DP 解法即可。
http://www.geeksforgeeks.org/dynamic-programming-set-21-box-stacking-problem/