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:
Input:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
Output: 6
方法1:
思路:
- 通过横向和纵向循环计算每一行所形成的直方图:直方图高度代表在该点建立的最大长方体高度
- 对于每一行的histogram,call一次84题的largestRectangleArea。循环结束返回搜索到的maxArea
?可是和dp有什么关系?
code
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) return 0;
int m = matrix.size();
int n = matrix[0].size();
vector<int> histogram(n, 0);
int maxArea = 0;
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
if (matrix[i][j] - '0' == 0){
histogram[j] = 0;
}
else {
histogram[j] ++;
}
}
// printVector(histogram);
maxArea = max(maxArea, largestRectangleArea(histogram));
}
return maxArea;
}
private:
int largestRectangleArea(vector<int> &height) {
int ret = 0;
height.push_back(0);
vector<int> index;
for(int i = 0; i < height.size(); i++)
{
while(index.size() > 0 && height[index.back()] >= height[i])
{
int h = height[index.back()];
index.pop_back();
int sidx = index.size() > 0 ? index.back() : -1;
if(h * (i-sidx-1) > ret)
ret = h * (i-sidx-1);
}
index.push_back(i);
}
return ret;
}
void printVector(vector<int> & A){
for (int i = 0 ; i < A.size(); i++)
cout << A[i] << " " ;
cout << endl;
}
};