【Leetcode】85. Maximal Rectangle(求最大矩形)(动态规划)

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

Example:

Input:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
Output: 6

题目大意:

给出一个二维矩阵,求出其中全为‘1’的最大矩形的面积。

解题思路:

本题紧接第84题。

84题题解:https://blog.csdn.net/qq_29600137/article/details/89069243

84题是前提假设了他们的高度在一个水平线上,求出最大矩形。同样本题也是求出最大矩阵,其相互之间一定有联系。我们可以将这个二维矩阵通过一层一层的依次查看之后我们就可以看出其实最大矩阵出现在第一层到第三层中,其地位位于同一个水平线上,所以我们可以一次遍历每一层,传入前初始化好每一层该列底部连续1的个数。


class Solution {
private:
int largestRectangleArea(vector& heights) {
        int n = heights.size();
        vector l(n,0),r(n,n);
        for(int i = 1;i=0&&heights[p]>=heights[i]){     
                p = l[p] - 1;
            }
            l[i] = p + 1;
        }
        for(int i = n-2;i>=0;i--){
            int p = i+1;
            while(p=heights[i]){
                p=r[p];
            }
            r[i] = p;
        }
        int ans = 0;
        for(int i = 0;i>& matrix) {
        if(matrix.size()==0) return 0;
        int maxans = 0;
        int n = matrix.size(), m = matrix[0].size();
        vector> matrix_num(n,vector(m,0));
        for(int i=0;i

 

你可能感兴趣的:(【LeetCode】刷题记录)