[LeetCode]85. Maximal Rectangle
题目描述
思路
直方图做法
将每一行看做一个直方图
如例子中的
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
可以看做
1 0 1 0 0
2 0 2 1 1
3 1 3 2 2
4 0 0 3 0
之后类似于直方图的做法,对每一行处理,同时维护一个最大值即可
直方图做法参考另一篇
[LeetCode]84. Largest Rectangle in Histogram
代码
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.size() == 0)
return 0;
int row = matrix.size(),
col = matrix[0].size(),
res = 0;
vector<int> h(col, 0);
for (int i = 0; i < row; ++i) {
stack<int> s;
int count = 0;
for (int j = 0; j < col; ++j) {
if (matrix[i][j] == '1')
++h[j];
else
h[j] = 0;
if (s.empty() || s.top() <= h[j]) {
s.push(h[j]);
}
else {
while (s.size() && s.top() >= h[j]) {
++count;
res = max(res, count * s.top());
s.pop();
}
while (count) {
s.push(h[j]);
--count;
}
s.push(h[j]);
}
}
while (s.size()) {
++count;
res = max(res, s.top() * count);
s.pop();
}
}
return res;
}
};
int main() {
vector<vector<char>> matrix = {{'1', '0'}};
Solution s;
cout << s.maximalRectangle(matrix) << endl;
system("pause");
return 0;
}
本文详细解析了LeetCode上第85题“最大矩形”的算法实现,采用类似直方图的方法处理二维矩阵,通过逐行构建高度数组并计算最大矩形面积,最终找到矩阵中全为1的最大矩形区域。
467

被折叠的 条评论
为什么被折叠?



