CareerCup 递归与动态规划 Q9.10 最大高度堆箱子

来源:互联网 发布:浙大宁波软件学院 编辑:程序博客网 时间:2024/05/24 03:37

给你一堆n个箱子,箱子宽wi、高hi、深di。箱子不能翻转,将箱子堆起来时,下面箱子的宽度、高度和深度必须大于上面的箱子。实现一个方法,撘出最高的一堆箱子,箱堆的高度为每个箱子高度的总和。

分析:用递归,子问题为以某一个箱子为底的高度最高的塔,确定底后,找到一个可以放在底上的箱子,再递归求解子问题。

注意:存在重复子问题,考虑用动态规划,用表记录中间结果,以便之后查询。

package cci;import java.util.ArrayList;class Box{int height;int width;int depth;public Box(int height, int width, int depth){this.height=height;this.width=width;this.depth = depth;}public boolean canBeAbove(Box box){if(box==null)return true;if(height<box.height && width<box.width && depth<box.depth)return true;return false;}public void print(){System.out.println(height+" "+width+" "+depth);}}public class CCI_9_10 {public static ArrayList<Box> maxBoxTower(Box[] boxes){return maxBoxTower(boxes, null);}private static ArrayList<Box> maxBoxTower(Box[] boxes, Box bottom){ArrayList<Box> maxTower = new ArrayList<Box>();int maxHeight = 0;//尝试每一个箱子for(int i=0; i<boxes.length; i++){//找到可以放在bottom上的箱子if(boxes[i].canBeAbove(bottom)){//以找到的箱子为底求解子问题(注意,这里的子问题会被重复求解,提高效率的办法是动态规划)ArrayList<Box> newTower = maxBoxTower(boxes, boxes[i]);//利用子问题的解构造当前问题的解int newHeight = calTowerHeight(newTower);if(newHeight>maxHeight){maxHeight = newHeight;maxTower = newTower;//以boxes[i]为底的最高塔}}}if(bottom != null){maxTower.add(0, bottom);}return maxTower;}private static int calTowerHeight(ArrayList<Box> tower){int height=0;for(Box box : tower){height += box.height;}return height;}public static void main(String[] args) {// TODO Auto-generated method stubBox[] boxes = new Box[3];boxes[0] = new Box(1,1,1);boxes[1] = new Box(2,2,2);boxes[2] = new Box(3,3,3);ArrayList<Box> result = maxBoxTower(boxes);for(Box item : result){item.print();}}}


0 0
原创粉丝点击