[LeetCode] 85. Maximal Rectangle

LeetCode最大矩形题解
本文提供了解决LeetCode上最大矩形问题的两种方法:一种是通过遍历二维数组并利用最大直方图面积的方法求解;另一种是采用动态规划的方法。这两种方法都详细解释了如何找到矩阵中最大的全由1构成的矩形。

https://leetcode.com/problems/maximal-rectangle/

思路一:这道题和前面那道 84. Largest Rectangle in Histogram 类似,遍历二维数组,生成一个 heights 数组,然后用 Largest Rectangle in Histogram 一样的方法做。

public class Solution {
    public int maximalRectangle(char[][] matrix) {
        int result = 0;
        if (matrix == null || matrix.length == 0) {
            return result;
        }
        int[] heights = new int[matrix[0].length];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (matrix[i][j] == '0') {
                    heights[j] = 0;
                } else {
                    heights[j] += 1;
                }
            }
            result = Math.max(result, helper(heights));
        }
        return result;
    }
    
    private int helper(int[] heights) {
        int result = 0;
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < heights.length; i++) {
            while (!stack.isEmpty() && heights[stack.peek()] >= heights[i]) {
                int tmp = stack.pop();
                int height = heights[tmp];
                int width = stack.isEmpty() ? i : i - stack.peek() - 1;
                result = Math.max(result, height * width);
            }
            stack.push(i);
        }
        while (!stack.isEmpty() && heights[stack.peek()] >= 0) {
            int tmp = stack.pop();
            int height = heights[tmp];
            int width = stack.isEmpty() ? heights.length : heights.length - stack.peek() - 1;
            result = Math.max(result, height * width);
        }
        return result;
    }
}

 

思路二:Dynamic Programming - https://discuss.leetcode.com/topic/6650/share-my-dp-solution

转载于:https://www.cnblogs.com/chencode/p/maximal-rectangle.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值