[LeetCode]85. Maximal Rectangle

来源:互联网 发布:网络营销效果优化研究 编辑:程序博客网 时间:2024/06/05 22:56

[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;}
0 0
原创粉丝点击