两种方法,第一种参考 http://blog.csdn.net/fightforyourdream/article/details/17711893
Time O(n^3), Space O(n^2)
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
int rows = matrix.size();
if(rows == 0) return 0;
int cols = matrix[0].size();
vector<vector<int> > ones(rows, vector<int>(cols, 0));
for(int i=0; i<rows; i++)
{
for(int j=0; j<cols; j++)
{
if(matrix[i][j] == '1')
{
if(j == 0)
ones[i][j] = 1;
else
ones[i][j] = ones[i][j-1]+1;
}
}
}
int max_area = 0;
for(int i=0; i<rows; i++)
{
for(int j=0; j<cols; j++)
{
if(ones[i][j] != 0)
{
int minWidth = ones[i][j];
int idx = i;
while(idx >= 0)
{
minWidth = min(minWidth, ones[idx][j]);
int area = minWidth * (i-idx+1);
max_area = max(max_area, area);
idx--;
}
}
}
}
return max_area;
}
};
第二种,利用了 Largest Rectangle in Histogram的答案。逐行求解。Time O(n^2), Space O(n)。
http://www.cnblogs.com/lichen782/p/leetcode_maximal_rectangle.html
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
int rows = matrix.size();
if(rows == 0) return 0;
int cols = matrix[0].size();
vector<int> heights(cols, 0);
int result = 0;
for(int i=0; i<rows; i++)
{
for(int j=0; j<cols; j++)
{
if(matrix[i][j] == '1')
heights[j]++;
else
heights[j] = 0;
}
int res = largestRectangleArea(heights);
result = max(result, res);
}
return result;
}
int largestRectangleArea(vector<int> &height) {
const int n = height.size();
if(n == 0) return 0;
int max_area = 0;
int area_top = 0;
int idx = 0;
stack<int> hists;
while(idx < n)
{
if(hists.empty() || height[idx] >= height[hists.top()])
hists.push(idx++);
else
{
int top = hists.top();
hists.pop();
int area_top = height[top]*(hists.empty()?idx:(idx-hists.top()-1));
max_area = std::max(max_area, area_top);
}
}
while(!hists.empty())
{
int top = hists.top();
hists.pop();
int area_top = height[top]*(hists.empty()?idx:(idx-hists.top()-1));
max_area = std::max(max_area, area_top);
}
return max_area;
}
};