【LeetCode】解题120:Triangle

Leetcode-Dynamic Programming题目总结 动态规划Dynamic Programming:通过把原问题分解为相对简单的子问题的方法来求解复杂问题的方法。 把求解的问题分成多个阶段或多个子问题,然后按照顺序求解各子问题。前一子问题的解,为后一问题的求解提供了有用信息。依次解决各个子问题,最后一个阶段的解就是初始问题的解。 动态规划问题,大致可以通过以下4个步骤: 1)划分状态,即划分子问题 2)状态表示,即如何让计算机理解子问题。 ... 阅读详情

Problem 120: Triangle [Medium]

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

[
    [2],
   [3,4],
  [6,5,7],
 [4,1,8,3]
]

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

Note:

Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

来源:LeetCode

解题思路

本题使用动态规划思想,与题解119:Pascal’s Triangle II类似。
题中要求只使用 O ( n ) O(n) O(n)的额外空间,按动规的思想,只需保存一个长度为 n n n的数组,每一层计算时从后往前计算,minlist(j)只需要用到上一层的minlist(j)和minlist(j-1),而且修改minlist(j)后不会影响到minlist(j-1)的计算,因此只需要 O ( n ) O(n) O(n)的空间即可。
公式为:
m i n l i s t ( j ) = { m i n l i s t ( j ) + t r i a n g l e ( i , 0 ) j = 0 ; m i n l i s t ( j − 1 ) + t r i a n g l e ( i , i ) j = i ; min ⁡ { m i n l i s t ( j − 1 ) , m i n l i s t ( j ) } + t r i a n g l e ( i , j ) o t h e r w i s e . minlist(j) = \begin{cases} minlist(j) + triangle(i,0) & j = 0;\\ minlist(j-1) + triangle(i,i) & j = i;\\ \min\{minlist(j-1), minlist(j)\} + triangle(i,j) & otherwise. \end{cases} minlist(j)=⎩⎪⎨⎪⎧​minlist(j)+triangle(i,0)minlist(j−1)+triangle(i,i)min{minlist(j−1),minlist(j)}+triangle(i,j)​j=0;j=i;otherwise.​
其中, i i i代表层数, m i n l i s t ( j ) minlist(j) minlist(j)代表到达第 j j j个数的最小路径,数组 m i n l i s t minlist minlist的更新是in-place的。
最后计算出第n层后,只需返回minlist中的最小值。

运行结果:
在这里插入图片描述
要点:动态规划

Solution (Java)

class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int N = triangle.size();
        int[] minlist = new int[N];
        minlist[0] = triangle.get(0).get(0);
        for(int i = 1; i < N; i++){
            minlist[i] = minlist[i-1] + triangle.get(i).get(i);
            for(int j = i-1; j > 0; j--){
                minlist[j] = Math.min(minlist[j], minlist[j-1]) + triangle.get(i).get(j);
            }
            minlist[0] = minlist[0] + triangle.get(i).get(0);
        }
        return Arrays.stream(minlist).min().getAsInt();
    }
}
Leetcode 120 Triangle 三角形最小路径和 给出一个三角形(数据数组),找出从上往下的最小路径和。每一步只能移动到下一行中的相邻结点上。空间复杂度要求O(n)。 阅读详情

相关推荐

TriangleProblem_java语言三角形问题

TriangleProblem_java语言三角形问题

Triangle Problems

Triangle Problem songxiuhuan 宋修寰 Import the Junit and eclemma Choose the project and right click, choose the build path and choose the Junit and hamcrest. Install eclemma Help——install newsof...

weixin_30654583的博客 252

从配置字到实际运动:手把手教你用EtherCAT调试伺服电机的控制模式(以倍福TwinCAT3为例)

本文详细介绍了如何使用EtherCAT调试伺服电机的控制模式,以倍福TwinCAT3为例。从环境搭建、模式配置到状态机切换,提供了完整的操作指南和典型故障排查方法,帮助工程师快速解决‘配置字写入了但电机不转’等常见问题,提升工业自动化现场的调试效率。

weixin_42783709的博客 419

软件测试实验1 — Junit 安装与 triangle problem 的测试

1. Install Junit(4.12), Hamcrest(1.3) with Eclipse 选中新建的项目,右键->Propertise->Java Build Path->Add External JARs 然后选中之前下好的junit-4.12.jar与hamcrest-core-1.3.rc2.jar 点击OK即引入成功 2. ...

b3627319730的博客 486

UNITE真菌数据库使用避坑指南:从下载到注释的完整流程

本文提供了UNITE真菌数据库从下载到注释的完整实战指南。针对真菌ITS序列分析,重点解析了数据库版本选择、格式转换的常见陷阱,并详细介绍了如何训练优化的sklearn分类器以提升物种注释的精度和可靠性,帮助用户构建高效稳定的本地工作流。

weixin_29240343的博客 198

保姆级教程:手把手调试PX4Ctrl的油门映射与姿态控制(附ROS节点配置)

本文提供PX4Ctrl的深度调参指南,涵盖油门映射、姿态控制及ROS节点配置等关键环节。通过详细解析PX4控制器的核心逻辑、递归最小二乘法(RLS)参数估计及状态机设计,帮助开发者优化无人机飞控性能。附实战案例与安全调试建议,适合PX4开发者进阶学习。

weixin_30363981的博客 382

软件测试Lab1:Junit 安装与 triangle problem 的测试

一、Junit安装 1. 安装Junit(4.12)和hamcrest(1.3) 首先从maven仓库中下载junit-4.12.jar和hamcrest-all-1.3.jar。 在Eclipse中新建一个项目,和src同级新建一个lib文件夹,将上述两个下载的jar包复制过来。 选中其中一个jar包,右键 -> Build Path -> Add to Build...

anbing9968的博客 373

WhatsApp API接口的隐秘角落:从协议解析到自定义消息引擎

本文深入解析WhatsApp API接口的隐秘角落,从协议逆向工程到自定义消息引擎开发实战。通过分析WhatsApp的二进制XML协议和加密机制,构建超越官方API限制的自定义消息引擎,实现高效、灵活的即时通讯解决方案。文章还提供了企业级架构设计和风控规避策略,助力开发者突破官方限制,提升消息到达率和成本效益。

q3r4s5t的博客 761

Triangle问题及解法

问题描述: Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 示例:  given the following triangle [ [2], [3,4]

刘天的博客 1073

IAR9.30以上版本安装、注册、新建工程和配置过程详细介绍

IAR 一般是指一款嵌入式软件的集成开发环境,类似于 MDK-Keil 这款软件。IAR 对于不同的内核处理器,是对应不同的 IAR 软件的,IAR 到目前为止支持大部分的MCU,比如8051系列、ARM架构系列、MSP430系列、AVR系列等等这些常用的芯片架构。对于 ARM 架构的芯片,有对应的 IAR Embedded Workbench for ARM 软件平台,因为我主要是使用 ARM 架构芯片,下面安装、注册和使用都是基于这个版本进行介绍的。

luobeihai的博客 6万+

从“能跑”到“好用”:一名 Python 开发者的工程化进阶之路【Python心得篇】

Python 早已不只是写脚本、跑数据的工具。后端服务AI Agent 编排层自动化平台核心语言数据与业务之间的“中枢层”区别只在于:你是用脚本方式,还是工程方式在写。如果你已经能写“能跑的 Python”,下一步,就是让它长期可跑、稳定可演进。Python 的真正价值不在于“写得快”,而在于能否支撑持续演进的工程实践。当代码从一次性脚本走向长期运行的系统,开发者必须从结构设计、职责拆分、性能意识和类型约束等方面进行系统性思考。

博客 1545

【LeetCode】120. Triangle

120. Triangle Description: Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle ...

Microstrong 3162

回归预测 | MATLAB实现基于贝叶斯线性回归(Bayesian Regression)的多变量输入回归预测

回归预测 | MATLAB实现基于贝叶斯线性回归(Bayesian Regression)的多变量输入回归预测

机器学习之心的博客,关注并私信文章链接,获取对应文章源码和数据。 2195

LeetCode --- 120. Triangle

120. Triangle Difficulty: Medium Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle ...

MissXy_的博客 462

SerDes学习笔记:DFE均衡架构示例(USB3.1、PCIe3.0\4.0)

本文探讨了DFE均衡器架构在不同数据接口中的应用特性。研究表明,抽头数量随数据速率提升而增加,1-16抽头架构较为常见。通过PCIeGen3/4实例分析,对比了单抽头、双抽头和15抽头DFE的性能差异,证明多抽头结构能通过精细调节有效提升噪声容限和降低误码率。文章详细阐述了DFE工作原理,包括其通过反馈信号对输入信号的补偿机制,以及不同抽头对消除码间干扰的作用。实验采用8Gbps速率(125ps/UI)进行波形仿真,直观展示了均衡处理前后的信号变化,为理解信道均衡技术提供了重要参考。

一只豌豆象的博客 517

深度学习工具包 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")

Leetcode 120 Triangle(DP)

题目连接:Leetcode 120 Triangle解题思路:dp[i][j] += min(dp[i+1][j], dp[i+1][j+1])。class Solution { public: int minimumTotal(vector&lt;vector&lt;int&gt;&gt;&amp; triangle) { int m = triangle.size(); fo...

不慌不忙、不急不躁 493

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

LeetCode 120. Triangle 解题报告

LeetCode 120. Triangle 解题报告题目描述Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.示例Example : The minimum path sum from top to

骆小坑的填坑之旅 630

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

【LeetCode】120. Triangle 解题报告(Python)

【LeetCode】120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址https://leetcode.com/problems/triangle/description/ 题目描述: Given a triangle, find the minimum path...

负雪明烛 2537

Leetcode 120. Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle [ [2], [3,4], [6,5...

hello world 209

【Leetcode】120. 三角形(Triangle)

Leetcode - 120 Triangle (Medium) 题目描述:给定一个三角形形状的集合,从上到下依次向邻接位置移动,求移动的最小路径和。 [ [2], [3,4], [6,5,7], [4,1,8,3] ] The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). ...

厉兵秣码 299

【LeetCode 面试经典150题】120. Triangle 三角形

Given a triangle array, return the minimum path sum from top to bottom.For each step, you may move to an adjacent number of the row below. More formally, if you are on index on the current row, you may move to either index or index on the next row.给定一个三

qq_43513394的博客 537

LeetCode: 120. Triangle

LeetCode: 120. Triangle 题目描述 Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle ...

杨领well的专栏 679

leetcode-120-Triangle 动态规划

问题题目:[leetcode-120]思路代码代码//c version int minimumTotal(int** triangle, int triangleRowSize, int *triangleColSizes){ int** dp = (int**)malloc( sizeof(int*) * triangleRowSize ); if( !dp ) r

Kang_TJU的博客 692

120. Triangle

120.Triangle Medium 3187325Add to ListShare Given atrianglearray, returnthe minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on indexion the current row, you may mo...

Sterben_Da的博客 190

LeetCode算法题之120. Triangle(Medium)【Python3题解】

题目描述: Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). Note: Bo

DaMoWangZQ的博客 398

[leetcode] 120. Triangle 解题报告

题目链接:https://leetcode.com/problems/triangle/ Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the

小榕流光的专栏 790
上一篇: 【LeetCode】解题119:Pascal's Triangle II
下一篇: 【LeetCode】解题121:Best Time to Buy and Sell Stock
Fayedy
博客等级 码龄11年 2粉丝 57原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值