【发布时间】:2015-12-12 12:04:03
【问题描述】:
在破解编码面试(第 5 版)中,提出了以下问题:
你有一叠 n 个宽度为 w(i)、h(i) 和 d(i) 的盒子。如果堆叠中的每个盒子在宽度、高度和深度上都严格大于其上方的盒子,则盒子不能旋转,只能堆叠在一起。实现一种方法来构建可能的最高堆栈,其中堆栈的高度是每个框的高度之和。
我想出了以下不涉及任何动态编程的递归解决方案:
public static List<Box> stackBoxes(List<Box> boxes){
if(boxes.size() <= 1){
return boxes;
}
List<Box> temp = new ArrayList<Box>();
temp = stackBoxes(boxes.subList(1, boxes.size()));
Box currentBox = new Box(0, 0, 0);
currentBox = boxes.get(0);
for(int i = 0; i < temp.size(); i++){
Box nextBox = new Box(0,0,0);
nextBox = temp.get(i);
if(nextBox.x >= currentBox.x && nextBox.y >= currentBox.y
&& nextBox.z >= currentBox.z){
List<Box> half1 = new ArrayList<Box>(temp.subList(0, i));
half1.add(currentBox);
List<Box> half2 = new ArrayList<Box>(temp.subList(i,
temp.size()));
half1.addAll(half2);
return half1;
}
}
List<Box> newStack = new ArrayList<Box>();
newStack.addAll(temp);
newStack.add(currentBox);
return newStack;
}
框类(x-width、y-height、z-depth):
public class Box {
public int x;
public int y;
public int z;
public Box(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
}
}
在我看来,盒子的最佳堆叠似乎总是只有一个,因为在堆叠中任何给定位置的任何盒子在宽度、高度和深度上都将等于或大于其上方的盒子。所以本质上,最佳堆叠将是一个有序列表,其中每个框
谢谢!
【问题讨论】:
-
只有一个“最高”的堆栈满足要求,但可以有多个组合满足基本约束同时更短。
标签: java oop recursion dynamic-programming