8.13 Stack of Boxes

来源:互联网 发布:算法导论 第三版 目录 编辑:程序博客网 时间:2024/06/06 17:38

First we have to sort the boxes by their height (descending), then we try to find each the max height for each box i as the bottom one and store their max height in a int[].

    public static int createStack(ArrayList<Box> boxes) {        Collections.sort(boxes, new BoxComparator());        int maxHeight = 0;        int[] mp = new int[boxes.size()];        for (int i = 0; i < boxes.size(); i++) {            int height = createStack(boxes, i,mp);            maxHeight = Math.max(maxHeight, height);        }        return maxHeight;    }    public static int createStack(ArrayList<Box> boxes, int bottomIndex,int[] mp) {        if(bottomIndex<boxes.size() && mp[bottomIndex] > 0) return mp[bottomIndex];        Box bottom = boxes.get(bottomIndex);        int maxHeight = 0;        for (int i = bottomIndex + 1; i < boxes.size(); i++) {            if (boxes.get(i).canBeAbove(bottom)) {                int height = createStack(boxes, i,mp);                maxHeight = Math.max(height, maxHeight);            }        }               maxHeight += bottom.height;        mp[bottomIndex] = maxHeight;        return maxHeight;    }    public static void main(String[] args) {        Box[] boxList = { new Box(6, 4, 4), new Box(8, 6, 2), new Box(5, 3, 3), new Box(7, 8, 3), new Box(4, 2, 2), new Box(9, 7, 3)};        ArrayList<Box> boxes = new ArrayList<Box>();        for (Box b : boxList) {            boxes.add(b);        }        int height = createStack(boxes);        System.out.println(height);    }
0 0
原创粉丝点击