Leetcode: 85. Maximal Rectangle

Description

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

Given the following matrix:

    1 0 1 0 0
    1 0 1 1 1
    1 1 1 1 1
    1 0 0 1 0
    
Return 6.

思路

  • 把这个矩阵分成第一行,第一二行,第一二三行。。来看,
  • 然后用84中的栈的方法求出当前的最大矩阵即可。

代码

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        int m = matrix.size();
        if(m == 0) return 0;
        int n = matrix[0].size();
        if(n == 0) return 0;
        
        vector<int> nums(n, 0);
        int res = 0;
        for(int i = 0; i < m; ++i){
            for(int j = 0; j < n; ++j){
                if(matrix[i][j] == '1')
                    nums[j] += 1;
                else nums[j] = 0;
            }
            res = max(res, maxRectangle(nums, n));
        }
        
        return res;
    }
    
    int maxRectangle(vector<int>&nums, int len){
        stack<int> stk;
        int res = 0;
        int h = 0, t = 0;
        for(int i = 0; i < len; ++i){
            while(!stk.empty() && nums[stk.top()] > nums[i]){
                h = nums[stk.top()];
                stk.pop();
                
                t = stk.empty() ? i : i - stk.top() - 1;
                res = max(res, h * t);
            }
            stk.push(i);
        }
        
        while(!stk.empty()){
            h = nums[stk.top()];
            stk.pop();
            
            t = stk.empty() ? len : len - stk.top() - 1;
            res = max(res, h * t);
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/lengender-12/p/7003838.html