"title"
Topic link
Given a 2D binary matrix filled with 0 "s and 1 ' s, find the largest rectangle containing only 1 's and return their 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 "Analysis"
Runtime
At first I think it can be a dynamic planning idea, such as:
MATRIX[I-1][J-1]–>MATRIX[I][J] or
MATRIX[I-1][J-1],MATRIX[I-1][J],MATRIX[I][J-1]–>MATRIX[I][J]
After several thoughts and practice, it seems that it is not going through
(Note: But this kind of thought is OK in 221.Maximal Square , the solving is detailed as follows: Leetcode the analysis _221. Maximal Square (graphic analysis))
Later found on a question 84. Largest Rectangle in histogram(see the solution to the details: Leetcode analysis _84. Largest Rectangle in histogram) the idea of dynamic programming to solve this problem
Leetcode put them together is really good hard.
is to use each line as a bottom, apply 84 of the practice, on AC
For example:
1 0 0 1 1
1 0 1 1 1
0 1 1 1 0
0 1 1 1 1
First line: heights[]: 1 0 0 1 1
Second line: heights[]: 2 0 1 2 2
Third line: heights[]: 0 1 2 3 0
Line Fourth: 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) * H
eights[Temp[top]];
top--;
Max_area = max (Max_area, cur);
} Temp[++top] = j;
} return Max_area; }
};