Recursively solve the problem and find the bottom of a box, and return the top heap of the box.
The DP thought is optimized. for situations where a box has already been obtained as the base, use a map to record it and then return it directly.
Pay attention to some clone and other language details.
Import Java. util. arraylist; import Java. util. hashmap; import Java. util. list; import Java. util. map; public class solution {public arraylist <Box> maxheight (Box [] boxes) {Map <box, arraylist <Box> cache = new hashmap <box, arraylist <Box> (); Return maxheight (boxes, null, cache);} private arraylist <Box> maxheight (Box [] boxes, box bottom, Map <box, arraylist <Box> cache) {// used to implement the DP idea. Note that each return value must be cloned; otherwise The results in the cache will also be changed by external reference. If (cache. containskey (bottom) Return (arraylist <Box>) cache. get (bottom ). clone (); int maxheight = 0; arraylist <Box> res = new arraylist <Box> (); For (INT I = 0; I <boxes. length; I ++) {If (boxes [I]. canabove (bottom) {// recursively solving the arraylist <Box> TMP = maxheight (boxes, Boxes [I], cache ); // calculate the heap height int curheight = calcu (TMP); If (curheight> maxheight) {curheight = maxheight; Res = TMP ;}}// current box Add if (bottom! = NULL) res. add (bottom); // put the result into the cache for DP cache. put (bottom, Res); Return res;} private int calcu (list <Box> List) {int res = 0; For (box each: List) {res + = each. h;} return res;} public static void main (string [] ARGs) {box [] boxes = {new box (3, 4, 1), new box (8, 6, 2), new box (7, 8, 3)}; system. out. println (new solution (). maxheight (boxes) ;}} class box {int W; int h; int D; public box (int w, int H, int d) {This. W = W; this. H = H; this. D = D;} Boolean canabove (Box B) {If (B = NULL) return true; return W <B. W & H <B. H & D <B. d ;}@ override Public String tostring () {return "box [W =" + W + ", H =" + H + ", D = "+ D +"] ";}}
9.10 n boxes, W, H, and D. The box cannot be flipped. The width, height, and depth of the box must be greater than the width, depth, and so on, build the highest pile of boxes.