第一种方法,单调栈,对每一行用一次单调栈,维护h数组,就会变成84题!!!!
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.size() == 0) return 0;
int n = matrix.size();
int m = matrix[0].size();
int maxx = 0;
stack<int>st;
vector<int>h(m + 1, 0);
for(int i = 0; i < n; ++ i){
for(int j = 0; j < m; ++ j){
if(matrix[i][j] == '1')
h[j]++;
else
h[j] = 0;
}
h[m] = 0;
while(!st.empty())
st.pop();
int pos = 0;
while(pos <= m){
if(st.empty() || h[st.top()] <= h[pos])
st.push(pos++);
else{
int cur = st.top();
st.pop();
int w;
if(st.empty())
w = pos;
else
w = pos - st.top() - 1;
maxx = max(maxx, w * h[cur]);
}
}
}
return maxx;
}
};
dp的做法, 高度依然是用单调栈那样维护, 那么, 对于每一行中的每一个数j,维护从j到最右边和到左边为1的范围,最后max(如果j 相应的位0, h数组也会是0, 所以不用担心)
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.size() == 0) return 0;
int n = matrix.size();
int m = matrix[0].size();
int maxx = 0;
vector<int>h(m, 0);
vector<int>l(m, 0);
vector<int>r(m, m - 1);
for(int i = 0; i < n; ++ i){
int left = 0, right = m - 1;
for(int j = 0, k = m - 1; j < m && k >= 0; ++ j, -- k){
if(matrix[i][k] == '1')
r[k] = min(r[k], right);
else{
r[k] = m - 1;
right = k - 1;
}
if(matrix[i][j] == '1'){
h[j] ++;
l[j] = max(left, l[j]);
}
else{
h[j] = 0;
l[j] = 0;
left = j + 1;
}
}
for(int j = 0; j < m; ++ j)
maxx = max(maxx, h[j] * (r[j] - l[j] + 1));
}
return maxx;
}
};