[leetcode] 221. Maximal Square @ python

电赛MSP430F5529之超声波测距+OLED 显示(含主要代码) 目录 前言 一、超声波介绍 二、部分代码 三、总结 题外话: 前言 哎,又双叒叕,电赛延期了,看起来像是遥遥无期,但是肯定要考虑大局,大家就继续抓紧时间学习知识,巩固自己的知识,更进一步。好了,今天主要是继承上一篇博文(OLED显示)写的,主要是写超声波测距的(US-015) 一、超声波介绍 利用TI公司的MSP430F5529单片机+超声波模块+OLED 实现 这里主要是利用单片机定时器的捕获功能来捕获超声波高电平持续时间,再计算得到距离,最后再在OLED 屏幕上显示出来,上图 阅读详情

原题

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

解法

参考: 花花酱 LeetCode 221. Maximal Square
动态规划. base case是当matrix长度为0时, 返回0. 构造dp数组, 将matrix里的字符串转化为数字, dp[i][j]表示以matrix[i][j]为右下角能构成的最大正方形的边长, 我们从第1行第1列开始, 求dp[i][j].

dp[i][j] = min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j]) + 1

然后找出二维数组dp中最大的值就是最大正方形的边, 取平方即可.
Time: O(mn)
Space: O(m
n)

代码

class Solution(object):
    def maximalSquare(self, matrix):
        """
        :type matrix: List[List[str]]
        :rtype: int
        """
        # base case
        if not matrix: return 0
        res = 0
        row, col = len(matrix), len(matrix[0])
        dp = [[1 if matrix[i][j] == '1' else 0 for j in range(col)] for i in range(row)]
        for i in range(1, row):
            for j in range(1, col):
                if matrix[i][j] == '1':
                    dp[i][j] = min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j]) + 1
                else:
                    dp[i][j] = 0
                    
        for row in dp:
            res = max(res, max(row))
        return res*res
能碳双控| AIRIOT智慧能碳管理解决方案 基于AIRIOT打造的智慧能碳管理平台解决方案结合大数据、物联网、人工智能(AI)、数字孪生等新一代信息技术,通过整合碳达峰、碳中和、实时碳价、碳配额和碳资产等多个模块,为组织提供了全方位、灵活且智能的碳资产管理解决方案,有助于实现碳管理目标、提升可持续性,并适应碳市场的不断变化。 阅读详情

相关推荐

四旋翼黑科技揭秘:如何利用PX4隐藏的角加速度数据提升控制性能

本文深入探讨了如何利用PX4飞控中隐藏的角加速度数据,结合增量非线性动态逆(INDI)控制方法,显著提升四旋翼无人机的控制性能。通过实战教程,指导开发者从数据订阅、INDI原理到代码实现,构建响应更快、鲁棒性更强的控制回路,有效应对突风与快速机动。

lake5的博客 721

Leetcode221. 最大正方形——python求解

题目: 在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。 示例: 输入: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 输出: 4 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/maximal-square python暴力求解 class Solution: def maximalSquare(self, matrix: List[List[str]]) -&

weixin_41729258的博客 555

拯救者R7000P(2021)装双系统Ubuntu20.04 解决联发科MT7921无线网卡在Ubuntu中不能联网

拯救者R7000P(2021)装双系统Ubuntu20.04/Ubuntu18.04 电脑配置:联想拯救者R7000P CPU:AMD R7-5800H GPU:RTX3060-6G 内存:16GB 固态:500G(原装)+500(加装) 1.做系统盘(本文以Ubuntu20.04为例) 1.下载Ubuntu20.04镜像 直接去Ubuntu官网或者一些国内的镜像去下载都可以,这里给出一个网址https://ubuntu.com/download/desktop,根据需要下载自己学要的Ubuntu版本,后缀

qq_41108639的博客 1万+

LeetCode 221. 最大正方形 | Python

使用动态规划,找出最长边,进而解决《221. 最大正方形》问题

"大梦三千秋的博客 1289

手把手教你用Gazebo和VINS-MONO搞定VIO SLAM仿真(附Realsense D435i模型配置)

本文详细介绍了如何使用Gazebo和VINS-MONO构建VIO SLAM仿真环境,包括Realsense D435i模型的配置与集成。通过实战指南,帮助开发者快速搭建高保真仿真平台,优化VIO性能,并解决常见问题,适用于机器人感知与定位导航领域。

weixin_30682415的博客 159

mac(apple silicon)arm64安装spm12详细教程

3.下载matlab runtime R2023b for macOS (macA64),注意必须下载这个,只下载matlab是不可以的。默认安装目录是/Applications/MATLAB/MATLAB_Runtime/R2023b。注意最后的命令,路径根据自己的matlab_runtime安装位置进行调整,然后就可以安装成功了。5. 解压spm12.zip,解压后将文件夹拖到应用程序下(Applications)2.下载spm12,这个版本可兼容mac芯片!6.打开mac终端,输入。

weixin_62332001的博客 2025

leetcode221.最大正方形 Python

题目: 在一个由 ‘0’ 和 ‘1’ 组成的二维矩阵内,找到只包含 ‘1’ 的最大正方形,并返回其面积。 示例: 输入: matrix = [[“1”,“0”,“1”,“0”,“0”],[“1”,“0”,“1”,“1”,“1”],[“1”,“1”,“1”,“1”,“1”],[“1”,“0”,“0”,“1”,“0”]] 输出:4 思路: 动态规划 定义一个动态矩阵,其中每个位置表示以当前位置为右下角,能够得到的最大正方形的边长。 初始化为全0,然后遍历矩阵,当遍历位置的数为0时直接跳过即可。 当遍历位

qq_36849855的博客 416

AFC自动售检票系统与人工智能AI结合的关键应用方案

针对售检票、大客流管理、设备运维及服务优化提供了可落地的技术支持和实现细节,可作为地铁智慧交通项目的实践参考

leijinquan01的博客 1513

leetcode-221 最大正方形 Python

方法一:动态规划 class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if not matrix:return 0 m = len(matrix) n = len(matrix[0]) res = 0 dp = ...

Xenonon的博客 452

Autojs实战教程---番茄免费小说Apk文件和源码

邀请码:782383363 字节跳到的App,推荐给大家,还是值得用一用的。不废话直接代码。 代码是带UI的复制后可以直接使用。 "ui"; //#region UI var rootUrl = "http://114.115.220.1:91";//各位大神小弟自己的服务器别黑谢谢 var storaySign = "FanqieXiaoShuo0412326@163.com"; var woolStorage = storages.create(storaySign);//创建本地存储 var

zy0412326的专栏 2万+

告别Vivado自带编辑器!手把手教你用Sublime Text 4 + Icarus Verilog搭建FPGA开发环境(Windows 10/11)

本文详细介绍如何在Windows 10/11系统下,使用Sublime Text 4和Icarus Verilog搭建高效的FPGA开发环境,替代Vivado自带编辑器。通过配置语法检查、代码高亮和智能补全等功能,提升Verilog开发效率,实现专业级工作流。

weixin_30684743的博客 428

python最大正方形_DP-LeetCode221. 最大正方形

1、题目描述在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。2、代码详解class Solution(object):def maximalSquare(self, matrix):if not matrix:return 0res = 0 # 记录结果# 定义dp数组,每个元素代表当前位置可以达到的最大的正方形的边长# 长宽都多补了一行一列是为了更方便处理边...

weixin_34252946的博客 371

【PX4学习笔记】1. ROS及PX4环境搭建

环境 Ubuntu18.04 安装教程参考 https://www.guyuehome.com/8983 安装过程中问题的解决 问题1 rosdep init 错误的终极解决方法 注意etc/下的ros和rostep文件夹要自己建 问题2 Ubuntu安装ROS报错 sudo: rosdep:找不到命令 问题3(更好地解决了问题1、2)【推荐】 解决GitHub的raw.githubusercontent.com无法连接问题 问题4:GeographicLib的安装 教程中安装GeographicLib d

【人工智障 | 计算鸡视觉 | 机器孩】 8234

Leetcode 221. Maximal Square (python+cpp)

Leetcode 221. Maximal Square题目解析:动态规划 题目 解析:动态规划 对于在矩阵内搜索正方形或长方形的题型,一种常见的做法是定义一个二维 dp 数组,其中 dp[i][j] 表示满足题目条件的、以 (i, j) 为右下角的正方形或者长方形的属性。对于本题,则表示 以(i,j)为右下角的全由1构成的最大正方形面积。如果当前位置是0,那么dp[i][j]即为0;如果 当前位置是1,我们假设dp[i][j]= k2,其充分条件为dp[i-1][j-1]、dp[i][j-1]和dp[i

qq_37821701的博客 506

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Folia 安装指南:如何在 Windows、macOS 与 Linux 上快速跑通全屏歌词动画

Folia 是一款把歌词渲染成全屏沉浸式动画的音乐播放器,本地曲库和在线音源都能播。想在 Windows、macOS 或 Linux 上装好桌面版、听到第一首歌,顺利的话 10 到 15 分钟就能搞定。咱们一步步来。 ## 动手前的三件事 - **确认系统**:桌面版基于 Electron,前后端环境都内置,装完即用。先弄清你在 Windows、macOS(Apple silicon)还是 L

gitblog_00580的博客 642

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

LeetCode 221.Maximal Square 动态规划

LeetCode 221.Maximal Square 题解 动态规划

Ace_15的博客 398

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Leetcode 221.最大正方形(Maximal Square)

Leetcode 221.最大正方形 1 题目描述(Leetcode题目链接)   在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。 输入: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 输出: 4 2 题解   本题为动态规划问题,起初的想法是构建一个DPDPDP矩阵,矩阵的元素含义为以该元素为右下角的最大正方形的面积...

qq_39378221的博客 240

[LeetCode 221] Maximal Square

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 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

coder 进阶的专栏 1464

Leetcode 221. Maximal Square Python3

题目描述: 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 动态规划方法...

dragonfly91的博客 204

LeetCode221. Maximal Square (python)

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 这是一道动态规划的题。...

AIpush的博客 333

Python Leetcode 221. Maximal Square 动态规划问题

Python Leetcode 221. Maximal Square 动态规划问题 这种题目肯定要用动态规划,像这种矩阵类型的,那么接下来就是找递推公式。 对于动态规划我也没有什么好的方法,就多做一点题吧,就有感觉了。 Done class Solution(object): def maximalSquare(self, matrix): """ :type matrix: List[List[str]] :rtype: int

GhostintheCode的博客 365

LeetCode 221. Maximal Square(最大正方形)

原题网址:https://leetcode.com/problems/maximal-square/ Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area. For example, given the foll

James Pan 1657

【LeetCode】221. Maximal Square 解题报告(Python & C++)

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

负雪明烛 5710

Leetcode 221 Maximal Square

class Solution: # @param {character[][]} matrix # @return {integer} def maximalSquare(self, matrix): if matrix == []: return 0 m, n = len(matrix), len(matrix[0])

Andrew9Tech的专栏 976

python leetcode 221. Maximal Square

class Solution(object): def maximalSquare(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ #dp[i][j]存储的是右下角坐标[i,j]的最大边长 if matrix =...

Neekity的博客 650

[leetcode] 221. Maximal Square

Description 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 分析 ...

Learning from the mistakes 197
上一篇: [leetcode] 55. Jump Game @ python
下一篇: [leetcode] 285. Inorder Successor in BST @ python
闲庭信步的空间
博客等级 码龄9年 86粉丝 416原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值