您的位置:首页 > 其它

Leetcode -- Maximal Rectangle

2015-10-27 10:56 120 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: