Maximal Rectangle
Given a 2D binary matrix filled with 0 's and 1 ' s, find the largest rectangle containing all ones and return to its area.
If you use DP to determine whether the (BEGIN1,END1) ~ (BEGIN2,END2) range is 1, it will time out.
For matrix matrices, build the height array row by line, calling largest Rectangle in histogram.
Build the height array method on the matrix I Line: for Height[j], that is, starting from matrix[i][j], up to 1 consecutive numbers of matrix[0][j].
classSolution { Public: intMaximalrectangle (vector<vector<Char> > &matrix) { if(Matrix.empty ())return 0; intresult =0; introw =matrix.size (); intCol = matrix[0].size (); for(inti =0; i < row; i + +) {//for ith vector, reduct to "largest Rectangle in histogram"vector<int> Height (col,0); for(intj =0; J < Col; J + +) { intIND =i; while(Ind >=0&& Matrix[ind][j] = ='1') {IND--; HEIGHT[J]++; }} result=max (result, Largestrectanglearea (height)); } returnresult; } intLargestrectanglearea (vector<int> &height) { if(Height.empty ())return 0; intresult =0; Stack<int> s;//elements in stack S is kept in ascending order intIND =0; while(Ind <height.size ()) { if(S.empty () | | height[ind]>=S.top ()) {S.push (height[ind]); } Else { intCount =0;//Pop Count while(!s.empty () && height[ind]<S.top ()) { inttop =S.top (); S.pop (); Count++; Result= Max (result, count*top); } for(inti =0; I <= count; i + +) S.push (Height[ind]); //Push count+1 times} IND++; } //All elements is in the stack s, and in ascending order intCount =0; while(!S.empty ()) {Count++; inttop =S.top (); S.pop (); Result= Max (result, count*top); } returnresult; }};
"Leetcode" maximal Rectangle