加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

LeetCode开心刷题三十二天——85. Maximal Rectangle

发布时间:2020-12-14 05:10:17 所属栏目:大数据 来源:网络整理
导读:85.?Maximal Rectangle Hard 1616 53 Favorite Share Given a 2D binary matrix filled with 0‘s and 1‘s,find the largest rectangle containing only 1‘s and return its area. Example: Input:[ ["1","0","1","0"],["1","1"],"0"]]Output: 6 IDEA: ONE
85.?Maximal Rectangle
Hard

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

Example:

Input:
[
  ["1","0","1","0"],["1","1"],"0"]
]
Output: 6

IDEA:
ONE IMPORTANT THING:
dp[i][j] means the number of "1" in i rows before j columns.
dp[1][2]代表在第一行中的第二列之前1的个数。
#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<climits>
using namespace std;
class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        //NULL judge very important
        int n1=matrix.size();
        if(n1==0) return 0;
        int n2=matrix[0].size();
        //dp[i][j] is the max number of 1 in columns j rows i
        //vector initializer special no need ==
        vector<vector<int>> dp(n1,vector<int>(n2));
        //initialization
        for(int i=0;i<n1;i++)
        {
            for(int j=0;j<n2;j++)
            {
                //nested function need to pay attention whether finish all procedure such as this finish one easy to forget the latter ?:
                dp[i][j]=(matrix[i][j]==1)?(j==0?1:dp[i][j-1]+1):0;
            }
        }

        int ans=0;

        for(int i=0;i<n1;i++)
        {
            for(int j=0;j<n2;j++)
            {
                int len = INT_MAX;
                for(int k=i;k<n1;k++)
                {
                    len=min(len,dp[k][j]);
                    if(len==0) break;
                    ans=max((k-i+1)*len,ans);
                }
            }
        }

        return ans;
    }
};

int main()
{
    vector<vector<char>> matrix=
    {
        {1,0,1,0},{1,1},0}
    };
    Solution s;
    int res=s.maximalRectangle(matrix);
    cout<<res<<endl;
    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读