[leetcode] 221. Maximal Square && 85. Maximal Rectangle

【信息科学与工程学】【数据科学】数据科学领域 第六篇 算法设计 07 堆、栈、表、矩阵、集合、队列、数组、字符串、树、图、动态规划、结构体、元组的算法01 当前段必须包含所有字符的最后出现位置。1. 字符串分割成最多片段2. 基因序列功能域划分3. 文本段落划分4. 音频声道分离5. 图像色彩分区6. 社交网络社群划分7. 蛋白质结构域8. 音乐乐章分段9. 代码模块划分10. 章节划分特征:一次扫描,贪心确定边界。 阅读详情

Maximal Square

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

Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4

解法

动态规划,找到每一个位置的可以达到的最大的正方形的边长。

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        if(matrix.empty() || matrix[0].empty())
            return 0;
        int m = matrix.size();
        int n = matrix[0].size();
        vector<vector<int> > dp(m, vector<int> (n, 0));
        int res = 0;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(i == 0 || j == 0)
                    dp[i][j] = matrix[i][j] == '1' ? 1:0;
                else{
                    if(matrix[i][j] == '1')
                        dp[i][j] = min(dp[i][j-1],min(dp[i-1][j],dp[i-1][j-1])) + 1;
                    else
                        dp[i][j] = 0;
                }
                res = max(res, dp[i][j]);
            }
        }
        return res*res;
    }
};

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.
Example:

Input:
[
[“1”,“0”,“1”,“0”,“0”],
[“1”,“0”,“1”,“1”,“1”],
[“1”,“1”,“1”,“1”,“1”],
[“1”,“0”,“0”,“1”,“0”]
]
Output: 6

直方图中最大的面积

可以把这个问题变成求直方图中最大的矩形面积;
对矩阵的每一行加上这行之前的所有行构成一个直方图heights,如果当前值为1,则heights[j]++,否则为0
对每一个直方图进行求最大面积值,最后得到的所有直方图的最大面积就是结果。

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        if(matrix.empty() || matrix[0].empty())
            return 0;
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> heights(n, 0);
        int res = 0;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(matrix[i][j] == '1')
                    heights[j] ++;
                else
                    heights[j]= 0;  
            }
            res = max(res,LargeRecinHisto(heights));
        }
        return res;
    }
    
    int LargeRecinHisto(vector<int> heights){
        stack<int> s;
        heights.push_back(0);
        int max_value = 0;
        for(int i=0;i<heights.size();i++){
            if(s.empty() || heights[i] >= heights[s.top()])
                s.push(i);
            else{
                while(!s.empty() && heights[i] < heights[s.top()]){
                    int cur = s.top(); 
                    s.pop();
                    max_value = max(max_value, heights[cur]*(s.empty() ? i : i-s.top()-1));
                }
                s.push(i);
            }   
        }
        return max_value;
    }
};

一个函数解决

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        if(matrix.empty() || matrix[0].empty())
            return 0;
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> heights(n+1, 0);
        int res = 0;
        for(int i=0;i<m;i++){
            stack<int> s;
            for(int j=0;j<n+1;j++){
                if(j<n)
                    heights[j] = matrix[i][j] == '1' ? heights[j]+1:0;
                while(!s.empty() && heights[j] <= heights[s.top()]){
                    int cur = s.top(); 
                    s.pop();
                    res = max(res, heights[cur]*(s.empty() ? j : j-s.top()-1));
                }
                s.push(j);
            }
        }
        return res;
    }
};

解法2

构造一个heights数组和解法1相同,然后再构造一个left和right数组
left数组表示:如果当前值matrix[i][j]==1,left[j]为与其相连都为1的左边界位置,否则为0;
right数组表示:如果当前值matrix[i][j]==1,right[j]为与其相连都为1的右边界位置+1,否则为n;
对于任意一个位置的[i][j],面积表示为(right[j]-left[j])*heights[j]。
举个栗子:

[
[1, 1, 0, 0, 1],
[0, 1, 0, 0, 1],
[0, 0, 1, 1, 1],
[0, 0, 1, 1, 1],
[0, 0, 0, 0, 1]
]

第0行:

h: 1 1 0 0 1
l: 0 0 0 0 4
r: 2 2 5 5 5

第1行:

h: 0 2 0 0 2
l: 0 1 0 0 4
r: 5 2 5 5 5

第2行:

h: 0 0 1 1 3
l: 0 0 2 2 4
r: 5 5 5 5 5

第3行:

h: 0 0 2 2 4
l: 0 0 2 2 4
r: 5 5 5 5 5

第4行:

h: 0 0 0 0 5
l: 0 0 0 0 4
r: 5 5 5 5 5

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        if(matrix.empty() || matrix[0].empty())
            return 0;
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> heights(n, 0), left(n, 0), right(n, n);
        int res = 0;
        for(int i=0;i<m;i++){
            int cur_left = 0, cur_right = n;
            for(int j=0;j<n;j++){
                if(matrix[i][j] == '1'){
                    heights[j]++;
                    left[j] = max(left[j], cur_left);
                }
                else{
                    heights[j] = 0;
                    left[j] = 0;
                    cur_left = j+1;
                }
            }
            
            for(int j=n-1;j>=0;j--){
                if(matrix[i][j] == '1')
                    right[j] = min(right[j], cur_right);
                else{
                    right[j] = n;
                    cur_right = j;
                }
                res = max(res, (right[j] - left[j]) * heights[j]);
            }
        }
        return res;
    }
};

解法3

先统计每一行的连续1的个数,使用一个数组 h_max, 其中 h_max[i][j] 表示第i行,第j个位置水平方向连续1的个数,若 matrix[i][j] 为0,那对应的 h_max[i][j] 也一定为0;
再次遍历每个位置,首先每个位置的 h_max 值都先用来更新结果 res,因为高度为1也可以看作是矩形,然后我们向上方遍历,上方 (i, j-1) 位置也会有 h_max 值,但是用二者之间的较小值才能构成矩形,用新的矩形面积来更新结果 res,这样一直向上遍历,直到遇到0,或者是越界的时候停止,这样就可以找出所有的矩形了。

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        if(matrix.empty() || matrix[0].empty())
            return 0;
        int m = matrix.size();
        int n = matrix[0].size();
        vector<vector<int> > h_max(m, vector<int> (n,0));
        int res = 0;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if (matrix[i][j] == '0') continue;
                if (j > 0) h_max[i][j] = h_max[i][j - 1] + 1;
                else h_max[i][0] = 1;
            }
        }
        for(int i=0;i<m;i++){
            for (int j = 0; j < n; ++j) {
                if (h_max[i][j] == 0) continue;
                int mn = h_max[i][j];
                res = max(res, mn);
                for (int k = i - 1; k >= 0 && h_max[k][j] != 0; --k) {
                    mn = min(mn, h_max[k][j]);
                    res = max(res, mn * (i - k + 1));
                }
            }
        }
        return res;
    }
};

参考

https://www.cnblogs.com/grandyang/p/4322667.html

WPF插件架构-如何动态加载封装好的第三方DLL的界面 插件架构中如何自动加载第三方DLL中的UI界面 阅读详情

相关推荐

别再折腾SNAP了!ENVI 5.6.0 直接拖拽打开Sentinel-2 L2A数据的正确姿势

本文详细介绍了ENVI 5.6.0直接处理Sentinel-2 L2A数据的高效方法,无需通过SNAP进行繁琐的重采样预处理。通过直接拖拽XML文件,用户可以快速加载不同分辨率的波段数据,显著提升工作效率。文章还对比了直接打开与SNAP重采样流程的优劣,并提供了常见问题解决方案和高级应用技巧。

weixin_30296405的博客 634

每周LeetCode算法题(八): 题目: 221. Maximal Square & 85. Maximal Rectangle

每周LeetCode算法题(八)题目1: 221. Maximal Square Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area. For example, given the following matri

JacKnights的博客 386

避坑指南:Unity与Visual Studio开发环境配置中的5个常见问题及解决方案

本文针对Unity与Visual Studio开发环境配置中的5个常见问题,提供了详细的解决方案。重点解决了项目文件生成失败导致命名空间无法识别、调试器无法附加、包管理器与扩展安装混乱、脚本编译错误以及多版本环境冲突等核心痛点,帮助开发者构建稳定高效的开发调试环境。

weixin_27791839的博客 279

LeetCode(85 & 221):最大矩形 Maximal Rectangle & 最大正方形 Maximal Square(Java)

2019.10.14 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新) github:https://github.com/ChopinXBP/LeetCode-Babel 这道题是之前做过的一道题的拓展题:LeetCode(84):柱状图中最大的矩形 Largest Rectangle in Histogram(Java) 从之前的解法思路出发可以有三种方法: 1.动态规...

NJU_ChopinXBP的博客 384

Spring Cloud 整合(一) CRUD

Springcloud 整合之 CRUDSpringcloud介绍功能概述为什么要选用Springcloud Springcloud介绍 功能概述 实现微服务 Spring Cloud为开发人员提供了工具,以快速构建分布式系统中的某些常见模式(例如,配置管理,服务发现,断路器,智能路由,微代理,控制总线,一次性令牌,全局锁,领导选举,分布式会话,群集状态)。分布式系统的协调导致样板式样,并且使用Spring Cloud开发人员可以快速站起来实现这些样板的服务和应用程序。 为什么要选用Springcloud

Kerwin-Lin的博客 1501

故障处理:Oracle一体机磁盘故障时磁盘组重平衡失败的故障处理

摘要: Oracle Exadata一体机出现磁盘故障案例,存储节点故障灯未亮但磁盘已产生大量坏块,导致重平衡失败。文章强调了一体机硬件巡检需检查6个关键维度:节点messages日志、存储cell告警日志、CellCLI日志、ASM告警日志、ILOM日志及服务器信号灯。故障分析显示硬盘物理故障导致磁盘组冗余受损,自动修复流程受阻。文中详细记录了通过CellCLI工具排查损坏磁盘的过程,并提供了完整的故障处理流程和命令输出。文章同步发布于微信公众号"IT民工的龙马人生"和博客网站(www

提供数据库技术支持(系统优化,故障处理,安装升级,数据恢复等) 1231

leetcode 84. Largest Rectangle in Histogram 、85. Maximal Rectangle 、221. Maximal Square

84. Largest Rectangle in Histogram https://www.cnblogs.com/grandyang/p/4322653.html 整体思路是递增不处理,当遇到减少时,计算之前所有大于当前高度的最优解。因为实际上只要遇到比你小的,就不可能以你为高度了。索引之间的差刚好能反应当前栈中高度所覆盖的区域,即宽度。 维护一个递增的栈,每次只用以当前栈的ind...

weixin_30569153的博客 191

第二篇:APS智能排产实战:OR-Tools与coptpy从入门到案例

专注于具体的技术实现,包括 OR-Tools 和 coptpy 的详细使用指南、建模技巧、日志解读,以及一个完整的两阶段生产排程案例。适合准备动手开发 APS 系统的工程师和研究者。

算法工程师 452

Leetcode 221 & 85

Leetcode 221 & 85Leetcode 221 Maximal SquareDescriptionGiven a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.For example, given the following

Zeongwan的博客 437

Harness Engineering:让Coding Agent真正落地生产

本文将带你系统性地了解如何让Coding Agent真正落地生产,核心是依托(全球领先的持续交付、云成本管理、 feature flagging、安全治理一体化平台),结合企业级AIDD(AI-Driven Development)的工程化实践,构建一套可信赖、可观测、可扩展、可治理的Coding Agent落地体系。核心概念与理论基础:什么是Coding Agent?它和普通的AI代码补全工具(比如GitHub Copilot)有什么区别?什么是Harness Engineering?

移动开发前沿的博客 455

Autosar诊断实战系列02-Dem(DTC&Event)要点及配置开发详解

Dem模块及其与Dcm等其他模块的交互是整个诊断Stack的重中之重,本文先对与其他模块的交互逻辑进行介绍,有一定掌握后继续重点介绍配置部分的开发。

initiallizer的博客 3330

leetcode 221. Maximal Square & 85. Maximal Rectangle

221. Maximal SquareGiven a 2D binary matrix filled with 0's and 1's, find the largest square 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

Crystal_Zero的博客 535

SPAD IMX479规格_VOP

对于VOP的定义,很多人可能是不理解这一路的供电,实际上这一路供电是非常重要的,这是给器件SPAD供电,决定SPAD是否work,在大部分的paper以及大部分公司,基本都是叫VOP,名称是SPAD breakdown voltage power supply,严格意义上叫Operating Voltage,工作电压。当然有些公司也有一些其他叫法就不提了。其实大家可以明显的看出,典型值-20.5没有发生变化,市面上绝大多数VOP的典型值也都是在-20V这边。

致力于lidar应用开发 701

[LeetCode]221. Maximal Square & 85. Maximal Rectangle

https://leetcode.com/problems/maximal-square/ https://leetcode.com/problems/maximal-rectangle/ 找到01数组中全为1的面积最大的正方形/长方形,返回最大面积 正方形: 二维DP非常简单 public class Solution { public int maxi

gqk289的专栏 257

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

【LeetCode】85. Maximal Rectangle 解题报告(Python)

作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/maximal-rectangle/description/ 题目描述: Given a 2D binary matrix filled with 0’s and 1’s, find the larges...

负雪明烛 4808

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

LeetCode 221. Maximal Square

DP问题,有点难想,但是理解以后不难。 记 dp[i][j] 为以 a[i][j] 为右下角的正方形的最大边长。 递推公式写起来不难,dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 if a[i][j]==1 如下图所示,较小的边+1后形成的正方形一定是包含在其他图形中的,也就是说都是1。 class S...

weixin_34088583的博客 88

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

LeetCode #221 - Maximal Square

题目描述:Given a 2D binary matrix filled with 0's and 1's, find the largest square 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 R...

LawFile的博客 285

LeetCode 85. Maximal Rectangle&221. Maximal Square--动态规划

题目链接 221. Maximal Square Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. For example, given the following matrix: 1 0 1 0

monkey_rose的博客 442

Leetcode刷题笔记-最大矩形,最大正方形

221.Maximal Square 思路: This problem can be solved by dynamic programming. They key to DP is the state equation. In this problem, we define the state asthe maximal size of the square that can be ...

Sengo的博客 746

[LeetCode] 34. Find First and Last Position of Element in Sorted Array Medium

Find First and Last Position of Element in Sorted Array Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. Your algorithm’s runti...

Peng_maple的博客 328

[LeetCode] 17. Letter Combinations of a Phone Number

Letter Combinations of a Phone Number Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A mapping of digit to letters (just ...

Peng_maple的博客 325

[leetcode] 139. Word Break

Word Break Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. N...

Peng_maple的博客 280

[leetcode] 97. Interleaving String

Interleaving String Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. Example 1: Input: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbcbcac” Output: true Example 2: Input: s1 =...

Peng_maple的博客 278

[LeetCode] 4. Median of Two Sorted Arrays

Median of Two Sorted Arrays There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). ...

Peng_maple的博客 263

[leetcode] 149. Max Points on a Line

Max Points on a Line Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. Example 1: Input: [[1,1],[2,2],[3,3]] Output: 3 Explanation: ^ | | o | ...

Peng_maple的博客 256

[LeetCode] 32. Longest Valid Parentheses

Longest Valid Parentheses Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring. Example 1: Input: “(()” Output: 2 Explan...

Peng_maple的博客 253
上一篇: [LeetCode] 78. Subsets && 90. Subsets II
下一篇: [leetcode] 87. Scramble String
Peng_maple
博客等级 码龄10年 0粉丝 79原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值