题目一:Largest Rectangle in Histogram
int largestRectangleArea(vector<int> &height){
height.push_back(0);//加入一个最小高度,用于清空最后栈中的所有数据
int length = height.size(),i = 0,maxArea = 0;
stack<int> stackIndex;
while(i < length)
{
if(stackIndex.empty() || height[i] >= height[stackIndex.top()])stackIndex.push(i++);//高度比前面的大,则进栈
else
{
int index = stackIndex.top();//弹出栈顶元素,并计算高度
stackIndex.pop();
int area = height[index] * (stackIndex.empty() ? i : (i - stackIndex.top() - 1));
maxArea = max(maxArea,area);
}
}
return maxArea;
}
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
int largestRectangleArea(vector<int> &height){
height.push_back(0);
int length = height.size(),i = 0,maxArea = 0;
stack<int> stackIndex;
while(i < length)
{
if(stackIndex.empty() || height[i] >= height[stackIndex.top()])stackIndex.push(i++);
else
{
int index = stackIndex.top();
stackIndex.pop();
int area = height[index] * (stackIndex.empty() ? i : (i - stackIndex.top() - 1));
maxArea = max(maxArea,area);
}
}
return maxArea;
}
int maximalRectangle(vector<vector<char> > &matrix) {
int row = matrix.size();
int col = matrix[0].size();
int i,j;
vector<vector<int> >dp(row);//dp[i][j]表示从第i个元素开始,包括第i个元素,向上数,直到遇到0时,1的个数,参考该博客
for(i = 0;i < row;i++)
{
vector<int> tmp(col);
dp[i] = tmp;
}
for(j = 0;j < col;j++)dp[0][j] = matrix[0][j] - '0';
for(i = 1;i < row;i++)
{
for(j=0;j < col;j++)
{
if(matrix[i][j] == '0')dp[i][j] = 0;
else dp[i][j] = dp[i-1][j] + 1;
}
}
int maxArea = 0;
for(i = 0;i < row;i++)
{
maxArea = max(maxArea,largestRectangleArea(dp[i]));
}
return maxArea;
}