085 Maximal Rectangle [Leetcode]

44 篇文章 0 订阅

题目内容:

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.

DP的过程还没有想清楚,先利用上一题的结果可以解决该问题。统计每一行为止向上有多少个连续的1做为bar的高度,对每一行调用Largest Rectangle in Histogram即可。

代码如下,运行时间32ms:

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        if(matrix.size() == 0 || matrix[0].size() == 0)
            return 0;

        int row(matrix.size()), col(matrix[0].size()), result(0);
        vector<vector<int>> heights(row, vector<int>(col));

        for(int i = 0; i < col; ++i)
            heights[0][i] = matrix[0][i] - '0';
        result = largestRectangleArea(heights[0]);

        for(int i = 1; i < row; ++i) {
            for(int j = 0; j < col; ++j) {
                heights[i][j] = (matrix[i][j] - '0') ? heights[i-1][j] + 1 : 0;
            }
            int temp(largestRectangleArea(heights[i]));
            result = result > temp ? result : temp;
        }

        return result;
    }

    int largestRectangleArea(vector<int>& height) {
        if(height.size() == 0) 
            return 0;
        //put a minimum number to calculate the area of last rectangle
        height.push_back(0);

        stack<int> h;
        int result(0), index(0), top(0);

        while(index < height.size()) {
            if(h.empty() || height[h.top()] < height[index]) {
                h.push(index++);
            }
            else {
                top = h.top();
                h.pop();
                //if stack had only 1 element, use index as width, else use current top index to calculate width
                top = h.empty() ? height[top] * index : height[top] * (index - h.top() - 1);
                result = result > top ? result : top;
            }
        }

        height.pop_back();
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值