【题目】
题目链接
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6
【分析】
runtime:
一开始觉得可以是动态规划的思想,比如:
matrix[i-1][j-1]–>matrix[i][j]或者
matrix[i-1][j-1],matrix[i-1][j],matrix[i][j-1]–>matrix[i][j]
经过几番思考实践,似乎走不通
(备注:但是这种思想在221.Maximal Square中是可以的,题解详见:leetcode题解分析_221. Maximal Square(图文分析))
后来发现上一道题84. Largest Rectangle in Histogram(详细思路题解见: leetcode题解分析_84. Largest Rectangle in Histogram)的动态规划的思想来解这道题
leetcode把他们放在一起还真的良苦用心。
就是将每一行当成底,套用84的做法,就AC了
比如:
1 0 0 1 1
1 0 1 1 1
0 1 1 1 0
0 1 1 1 1
第一行:heights[]: 1 0 0 1 1
第二行:heights[]: 2 0 1 2 2
第三行:heights[]: 0 1 2 3 0
第四行:heights[]: 0 2 3 4 1
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
int row = matrix.size();
if( row == 0 ) return 0;
int col = matrix[0].size();
vector< int > heights( col , 0 ) ;
int max_area = 0;
heights.push_back(0);
for( int i = 0 ; i < row ; i ++ ){
int top = 0, cur = 0;
vector<int> temp(heights.size() , 0);
temp[top] = -1;
for( int j = 0 ; j < heights.size() ; j++ ){
if( j != heights.size() ) heights[j] = matrix[i][j] == '1' ? 1 + heights[j] : 0;
while( top > 0 && heights[ temp[top] ] >= heights[j] ) {
cur= ( j - temp[top-1] - 1 )* heights[ temp[top] ] ;
top--;
max_area = max( max_area , cur );
}
temp[++top] = j;
}
}
return max_area;
}
};