leetcode题解分析_85. 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

【分析】

runtime:
这里写图片描述
一开始觉得可以是动态规划的思想,比如:


matrix[i-1][j-1]–>matrix[i][j]或者
matrix[i-1][j-1],matrix[i-1][j],matrix[i][j-1]–>matrix[i][j]


经过几番思考实践,似乎走不通
(备注:但是这种思想在221.Maximal Square中是可以的,题解详见:leetcode题解分析_221. Maximal Square(图文分析)


后来发现上一道题84. Largest Rectangle in Histogram(详细思路题解见: leetcode题解分析_84. Largest Rectangle in Histogram)的动态规划的思想来解这道题
leetcode把他们放在一起还真的良苦用心。
就是将每一行当成底,套用84的做法,就AC了


比如:
1 0 0 1 1
1 0 1 1 1
0 1 1 1 0
0 1 1 1 1
第一行:heights[]: 1 0 0 1 1
第二行:heights[]: 2 0 1 2 2
第三行:heights[]: 0 1 2 3 0
第四行:heights[]: 0 2 3 4 1


class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        int row = matrix.size();
        if( row == 0 )  return 0;   
        int col = matrix[0].size();
        vector< int > heights( col , 0 ) ;
        int max_area = 0;
        heights.push_back(0);
        for( int i = 0 ; i < row ; i ++ ){
            int top = 0, cur = 0;
            vector<int> temp(heights.size() , 0);
            temp[top] = -1;
            for( int j = 0 ; j < heights.size() ; j++ ){
                if( j != heights.size() )  heights[j] = matrix[i][j] == '1' ? 1 + heights[j] : 0;
                while( top > 0 && heights[ temp[top] ] >= heights[j] ) {
                    cur= ( j - temp[top-1] - 1 )* heights[ temp[top] ] ;
                    top--;
                    max_area = max( max_area , cur );
                }
                temp[++top] = j;
            }
        }
        return max_area;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值