LeetCode Maximal Rectangle(dp)



Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

题意:给出一个由字符0和1组成的二维字符数组,找到最大的矩阵,其所有字符为1

思路:动态规划,用left[n]表示所在行的第n个元素的左边界为1的下标,right[n]表示所在行的第n个元素的右边界的下标,height[n]表示所在行的第n个位置连续1的个数,即高度

         状态转移方程为

         left[n] = max{left[n], cur_left}

         right[n] = min{right[n], cur_right}

         height[n] = height[n] + 1 if matrix[row][col] = 1

  代码如下:

class Solution {
    public int maximalRectangle(char[][] matrix) {
        int row = matrix.length;
        if (row == 0) return 0;

        int col = matrix[0].length;
        int[] left = new int[col];
        int[] right = new int[col];
        int[] height = new int[col];

        Arrays.fill(right, col);

        int res = 0;
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                if (matrix[i][j] == '1') height[j]++;
                else height[j] = 0;
            }

            int cur_left = 0;
            for (int j = 0; j < col; j++)
            {
                if (matrix[i][j] == '1') left[j] = Math.max(left[j], cur_left);
                else {
                    left[j] = 0;
                    cur_left = j + 1;
                }
            }

            int cur_right = col;
            for (int j = col - 1; j >= 0; j--)
            {
                if (matrix[i][j] == '1') right[j] = Math.min(right[j], cur_right);
                else {
                    right[j] = col;
                    cur_right = j;
                }
            }

            for (int j = 0; j < col; j++)
            {
                res = Math.max(res, (right[j] - left[j]) * height[j]);
            }
        }
        return res;
    }
}

你可能感兴趣的:(LeetCode Maximal Rectangle(dp))