LeetCode85. Maximal Rectangle

本文详细解析了LeetCode 85题最大矩形问题,通过借用LeetCode 84题的解决方案,将每行视为直方图,逐步计算最大矩形面积。提供了完整的C++代码实现。

LeetCode85. Maximal Rectangle

原题地址

题目描述

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

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Return 6.

思路

 本题借用了LeetCode 84 Largest Rectangle in Histogram中的代码。
 将矩阵的每一行看出一个直方图,逐行求出其最大矩阵进行比较。
LeetCode 85

图片转自 http://blog.youkuaiyun.com/doc_sgl/article/details/11832965

代码实现

class Solution {
public:
     int largestRectangleArea(vector<int>& heights) {

        stack<int> index;
        heights.push_back(0);
        int res=0;
        for(int i=0;i<heights.size();++i){
          if( index.empty() || heights[i]>heights[index.top()]) index.push(i);
          else{
              int cur=index.top();
              index.pop();
              res=max(res,heights[cur]*(index.empty()?i:(i-index.top()-1)));
              --i;
          }
        }
        return res;
    }

    int maximalRectangle(vector<vector<char>>& matrix) {

       if (matrix.size()<=0 || matrix[0].size()<=0) return 0;  
       int row = matrix.size(); 
       int col = matrix[0].size();  
       vector<vector<int>> heights(row, vector<int>(col));  

       int maxArea = 0;  
       for(int i=0; i<row; i++){

        for(int j=0; j<col; j++) {  
            if (matrix[i][j]=='1'){  
                heights[i][j] = (i==0 ? 1 : heights[i-1][j] + 1);
            }  
        }  //构造每个0~i行构成的sub矩阵的直方图输入数据。

        maxArea = max(maxArea, largestRectangleArea(heights[i]));
    }  

    return maxArea;
    }
};

代码转自: http://blog.youkuaiyun.com/feliciafay/article/details/42293691

鸡汤

放长假心情有些浮躁,没刷题,这一题也看了很多题解才弄懂。还是要坚持一题一题的做,学的东西太多,继续加油,晚安。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值