8.13 Stack of Boxes

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);
    }

你可能感兴趣的:(recursion)