leetcode 221. 最大正方形   medium

leetcode 221. 最大正方形   medium          

题目描述:

在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。

示例:

输入: 

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

输出: 4

解题思路:

方法一:

第一反应就是用求最大矩形的方法做,也就是按行来求直方图的最大面积

方法二:

dp。

dp(i, j)=min(dp(i−1, j), dp(i−1, j−1), dp(i, j−1))+1 (if vec【i】【j】=1) 

dp(i,j)=0 (if vec【i】【j】=0)

dp【i】【j】 表示的含义是必须以i,j为右下角的 最大正方形的边长

代码:

// 单调栈
class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {

        if(matrix.empty() || matrix[0].empty())
            return 0;
        int res=0;
        // 按行来,用单调栈计算直方图的最大面积
        vector<int> vec(matrix[0].size(),0);
        
        for(int i=0;i<matrix.size();++i){
            
            for(int j=0;j<vec.size();++j){
                vec[j]= matrix[i][j]=='1'?vec[j]+1:0;
            }
            
            res = max(res,core(vec));
        }
        
        return res;

 
    }
    
    
    int core(const vector<int> & vec){
        int res=0;
        stack<int> stk;
        for(int i=0;i<vec.size();++i){
            while(stk.size() && vec[i]<=vec[stk.top()]){
                int index=stk.top();
                stk.pop();
                int end=i;
                int start=stk.empty()?-1:stk.top();
                
                int area= (end-start-1)>=vec[index]?vec[index]*vec[index]:0;

                res= max(res,area);
            }
            stk.push(i);
        }
        
        
        int end=vec.size();
        while(stk.size()){
            int index=stk.top();
            stk.pop();
            int start=stk.empty()?-1:stk.top();
            int area= (end-start-1)>=vec[index]?vec[index]*vec[index]:0;
            res= max(res,area);
        }
        
        return res;  
    }


};




//dp
class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {

        if(matrix.empty() || matrix[0].empty())
            return 0;
        int res=0;
        
        vector<vector<int>> dp(matrix.size(),vector<int>(matrix[0].size(),0));

        for (int i = 0; i < matrix.size(); ++i) {
            for (int j = 0; j < matrix[0].size(); ++j) {
                if (i == 0 || j == 0) dp[i][j] = matrix[i][j] - '0';
                else if (matrix[i][j] == '1') {
                    dp[i][j] = min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])) + 1;
                }
                res = max(res, dp[i][j]);
            }
        }
        return res * res;
            
        
            
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值