classSolution { public: intlargestRectangleArea(vector<int>& h){ int n = h.size(); vector<int> left(n), right(n); stack<int> stk;
for (int i = 0; i < n; i ++ ) { while (stk.size() && h[stk.top()] >= h[i]) stk.pop(); if (stk.empty()) left[i] = -1; else left[i] = stk.top(); stk.push(i); }
stk = stack<int>(); for (int i = n - 1; i >= 0; i -- ) { while (stk.size() && h[stk.top()] >= h[i]) stk.pop(); if (stk.empty()) right[i] = n; else right[i] = stk.top(); stk.push(i); }
int res = 0; for (int i = 0; i < n; i ++ ) { res = max(res, h[i] * (right[i] - left[i] - 1)); }
return res; }
intmaximalRectangle(vector<vector<char>>& matrix){ //思路就是固定底边,然后看从底边网上是否存在连续的1,如果存在记录长度,然后从中找出最大的矩形的面积,最后求出矩形面积的全局最大值。另外有递推公式:h(i,j) = 1 + h(i - 1,j) if(matrix.empty() || matrix[0].empty()) return0; //n表示高度,m表示宽度 int n = matrix.size(), m = matrix[0].size(); vector<vector<int>> h(n,vector<int>(m));//设置状态方程 for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) if(matrix[i][j] == '1'){ if(i) h[i][j] = 1 + h[i - 1][j];//如果i大于0,那么就是上述递推公式 else h[i][j] = 1; } int res = 0; for(int i = 0; i < n; i++) res = max(res, largestRectangleArea(h[i]));