Leetcode -- Maximal Rectangle

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

分析:

本题求解时借助了对直方图求最大矩形的解法。对每层生成一个累计直方图并求解。

class Solution {
public:
    int maxrec(vector<int> hist)
    {
        hist.push_back(0);
        stack<pair<int,int>> sta;
        int res;
        for(int i=0;i<hist.size();)
        {
            if(sta.empty()||sta.top().second<hist[i])
            {
                sta.push(make_pair(i,hist[i]));
                i++;
            }
            else
            {
                int j=sta.top().first,h = sta.top().second;
                sta.pop();
                int last;
                if(sta.empty()) last = -1;
                else last = sta.top().first;
                res = max(res,(i-last-1)*h);
            }
        }
        return res;
    }
    int maximalRectangle(vector<vector<char>>& matrix) {
        int n=matrix.size();
        if(n==0) return 0;
        int m=matrix[0].size();
        vector<int> hist(m,0);
        int mval=0;
        for(int i=0;i<n;++i)
        {
            for(int j=0;j<m;++j)
            {
                if(matrix[i][j]=='0') hist[j]=0;
                else hist[j]++;
            }
            mval = max(mval,maxrec(hist));
        }
        return mval;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值