9.10 叠箱子,不是很理解,建议做几道dp的leetcode题目

来源:互联网 发布:细雪哪个译本好 知乎 编辑:程序博客网 时间:2024/06/13 15:17

You have a stack of n boxes, with widths w., heights l\ and depths dr The boxes
cannot be rotated and can only be stacked on top of one another if each box in the
stack is strictly larger than the box above it in width, height, and depth. Implement
a method to build the tallest stack possible, where the heigh t of a stack is the sum of
the heights of each box. 答案cc150 165页



public ArrayList<Box> createStackDP(Box[] boxes, Box bottom,

2 HashMap<Box, ArrayList<Box» stack_map) {
3 if (bottom != null && stack_map.containsKey(bottom)) {
4 return stack_map.get(bottom);
5 }
6
int max_height = 0;
8 ArrayList<Box> max_stack = null;
9 for (int i = 0; i < boxes.length; i++) {
10 if (boxes[i].canBeAbove(bottom)) {
11 ArrayList<Box> new_stack =
12 createStackDP(boxes, boxes[i], stackjnap);
13 int new_height = stackHeight(new_stack);
14 if (newjieight > max_height) {
15 max_stack = new_stack;
16 max_height = newjieight;
17 }
18 }
19 }
20
21 if (max_stack == null) max_stack = new ArrayList<Box>();
22 if (bottom != null) max_stack.add(0, bottom);
23 stackjnap.put(bottomj max_stack);
24
25 return (ArrayList<Box>)max_stack.clone();
26 }
0 0
原创粉丝点击