LeetCode 85. Maximal Rectangle

看起来是 LeetCode 221. Maximal Square 的拓展,但是完全不能用那一题dp的思想。

最主要的问题是,矩形没法和正方形一样保证 较小的边+1后形成的矩形一定是包含在其他图形中。

 

二维的问题我们想办法转换为一维的问题去做。类似 LeetCode 363. Max Sum of Rectangle No Larger Than K

但是不同于这一题,我们不用枚举两个row,并累加之间的元素。本题我们从第一行累加到第 i 行 (不是直接累加,必须当前也是1才能累加,否则归零)。这样我们数组里每个元素的值都能保证这一列上有连续 heights[i] 个1,这些1可以构成矩形。

这样本题就转化为了 LeetCode 84. Largest Rectangle in Histogram 的问题。用 monotone stack O(n)。

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        int m=matrix.size(), n=m==0?0:matrix[0].size();
        int res=0;
        
        // stack rows
        vector<int> heights(n,0);
        for (int r=0;r<m;++r){
            for (int j=0;j<n;++j){
                if (matrix[r][j]=='0') heights[j] = 0;
                else heights[j]+=1;
            }
            
            // Largest Rectangle in Histogram
            heights.push_back(0);
            stack<int> s; // index stack
            for (int i=0;i<heights.size();++i){
                while (!s.empty() && heights[s.top()]>heights[i]){
                    int h=heights[s.top()]; s.pop();
                    int w;
                    if (s.empty()) w=i;
                    else w=i-s.top()-1;
                    res = max(res, h*w);
                }
                s.push(i);
            }
        }
        return res;
    }
};

时间复杂度 O(mn)

 

Related Problems

LeetCode 84. Largest Rectangle in Histogram

LeetCode 221. Maximal Square

LeetCode 363. Max Sum of Rectangle No Larger Than K

posted @ 2019-07-31 14:36  約束の空  阅读(162)  评论(0编辑  收藏  举报