LeetCode Triangle

论文笔记--Spatial-Temporal Fusion Graph Neural Networks for Traffic Flow Forecasting Summary 在交通预测问题上,现有的框架通常利用给定的空间邻接图和复杂的机制来建模空间和时间关联。作者认为使用给定的空间邻接图会限制模型的有效时空相关性学习,并且它们通常使用单独的模块来实现空间和时间相关性,或者只使用独立的组件来捕获局部或全局的异质依赖关系,割裂了时空依赖关系。为此作者提出一种时空融合图神经网络用于交通预测。提出一种数据驱动的“时间图”生成方法,以此来补偿空间图可能没有反映的相关性。提出一种新的交通预测方法。 Problem Definition 交通预测中的挑战 以上图为 阅读详情

LeetCode 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,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.


很明显、经典的DP问题。题目要求最好使用O(n)的空间来完成。

方法一:自顶向下,但是貌似空间利用率超过了O(n)
关键思想是逐层累计,用一个数组来保存累计的值。累计式:
arr[i] = min(arr[i-1] + triangle[i][j], arr[i] + triangle[i][j])//j表示第i行的下标
最后arr中最小值就是所要的结果。
int minimumTotal(vector<vector<int> > &triangle) 
{
	int m = triangle.size();
	if (m == 0)
		return 0;

	int n = triangle[m - 1].size();
	int *arr = new int[n];			
	arr[0] = triangle[0][0];
	
	//从第二行开始
	for (int i = 1; i < m; i++)
	{
		int col = triangle[i].size();	
		//零时存储的数组,以免改变了原来保存在arr中的数据
		int * tmpArr = new int[col];
		for (int j = 1; j < col - 1; j++)
			tmpArr[j] = (arr[j - 1] + triangle[i][j] <= arr[j] + triangle[i][j]) ? (arr[j - 1] + triangle[i][j]) : (arr[j] + triangle[i][j]);
		
		//把arr的最左边和最右边计算出来,以及把tmpArr的数据放到arr中
		arr[col - 1] = arr[col - 2] + triangle[i][col - 1];
		arr[0] += triangle[i][0];
		for (int j = 1; j < col - 1; j++)
			arr[j] = tmpArr[j];

		delete tmpArr;
	}
	//排个序,第一个就是最小的
	sort(arr, arr + n);
	int res = arr[0];
	delete arr;
	
	return res;
}
中间申请了tmpArr来保存零时的数据,以免叠加的时候arr数组部分数据被覆盖。



方法二:自底向上
int minimumTotal(vector<vector<int> > &triangle) {
    if (triangle.size() == 0)
		return 0;

	int m = triangle.size();
	int n = triangle[m - 1].size();

	int *arr = new int[n];
	//将三角形最底层一行的数据给arr初始化
	for (int i = 0; i < n; i++)
		arr[i] = triangle[m - 1][i];

	for (int i = n - 2; i >= 0; i--)
	{
		for (int j = 0; j <= i; j++)
		{
		    arr[j] = min(arr[j] + triangle[i][j], arr[j + 1] + triangle[i][j]);
		}
	}

	int res = arr[0];
	delete arr;
	return res;
    }
};


方法三:自底向上,不用空间。(参看人家的)

int minimumTotal(vector<vector<int> > &triangle) {  
        for (int i = triangle.size() - 2; i >= 0; --i)  
        {  
            for (int j = 0; j < triangle[i].size(); ++j)  
            {  
                triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]);  
            }  
        }  
        return triangle[0][0];  
    }  

Claude Code 新手安装指南,手把手教你怎么安装使用 如果你是企业内网用户,或者需要自定义 API 端点,那可以用手动配置 API Key 的方式。 阅读详情

相关推荐

文献阅读笔记:量子微波测量技术综述

量子微波测量技术研究进展:量子微波测量技术利用里德堡原子与微波电场的相干相互作用,突破了传统测量方法的物理限制。该技术基于电磁诱导透明效应和里德堡原子能级跃迁原理,通过激光激发原子并监测光谱变化来测量微波电场强度。相比传统方法,量子微波测量具有超高灵敏度(理论极限可达nV/cm)、宽动态范围(超过100dB)、小型化等显著优势,且测量结果可直接溯源至普朗克常数。典型实验系统包括光源、原子气室和探测器,采用光谱法、干涉法等多种测量方法。近年来,该技术在基础研究和应用方面取得重要进展,展现出在通信、雷达、计量等

Grow into a more wonderful you 988

Triangle - LeetCode

目录 题目链接 注意点 解法 小结 题目链接 Triangle - LeetCode 注意点 树是以vector的形式给出 贪心算法只能给出局部最优解而不是全局最优解,所以要用dp算法 解法 解法一:以triangle本身为dp数组,状态转移方程为triangle...

weixin_30719711的博客 180

Vivado实战:从零封装AXI-Lite接口的呼吸灯IP核

本文提供了一份详细的Vivado实战指南,手把手教你如何将Verilog编写的呼吸灯模块封装成带AXI-Lite接口的IP核。内容涵盖从创建IP框架、编写核心逻辑、连接AXI总线到在ZYNQ系统中调用并编写C程序进行软硬件协同测试的完整流程,是掌握FPGA软硬件协同设计的关键实践。

weixin_29233333的博客 596

Leetcode Triangle 解题报告

Leetcode Triangle  http://oj.leetcode.com/problems/triangle/ 一道动态规划的经典题,POJ 1163 也是同一类型题,唯一区别在于Leetcode求最小值,POJ 1163求最大值。 递推公式是关键,假设原数组可以被修改,递推公式为:array[i][j] = array[i][j] + Math.max(array[i-1][

算法的天空 3820

共享单车需求预测问题:建模篇

机器学习训练营——机器学习爱好者的自由交流空间(qq群号:696721295) 在上一篇里,我们使用可视化的方法分析了“共享单车”的数据集,理解了特征(变量)之间的关系。我们将在本篇建立几个模型预测单车的需求量,并比较它们的预测效果。 随机森林填充法 首先,导入必需的库、训练集和检验集。 import pylab import calendar import numpy as np impor...

wong2016的博客 1万+

SigmaStudio进阶技巧:如何用ADAU1701实现60段EQ与防啸叫算法

本文深入探讨了如何在ADAU1701 DSP芯片上实现专业级音频处理系统。通过精密的资源规划与架构设计,详细讲解了构建高达60段参数均衡器(EQ)的有效方法,并集成了移频与自适应陷波双策略的智能防啸叫算法。内容涵盖从SigmaStudio工程优化、算法模块组合到系统联调实战的全流程,旨在帮助中高级开发者充分利用ADAU1701性能,打造稳定、高效的音频处理解决方案。

weixin_28256233的博客 384

LeetCode120—Triangle

LeetCode120—Triangle

上善若水 528

newman的使用

Newman是一个基于Node.js的postman命令行工具,用于运行和测试PostmanAPI 请求的集合。它允许用户在命令行环境中执行Postman的JSON文件,从而实现接口自动化测试和持续集成,同时支持用户进行自动化测试、批量执行请求、生成报告等操作。

m0_62825058的博客 1615

【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

EMC基础知识总结

电磁干扰(Electromagnetic Interference),简称EMI,有和两种。传导干扰主要是电子设备产生的干扰信号通过导电介质或公共电源线互相产生干扰;辐射干扰是指电子设备产生的干扰信号通过空间耦合把干扰信号传给另一个电网络或电子设备。

学海无涯的专栏 1364

国科大学习资料--矩阵论(叶世伟)-期末考试题整理3

国科大学习资料–矩阵论-期末考试题整理3 国科大学习资料–矩阵论-期末考试题整理3 国科大学习资料–矩阵论-期末考试题整理3

无名何许人的博客 1402

【LeetCode】解题118:Pascal's Triangle

LeetCode解题 118:Pascal's Triangle Problem 118: Pascal's Triangle [Easy]解题思路Solution (Java) Problem 118: Pascal’s Triangle [Easy] Given a non-negative integer numRows, generate the first numRows of Pasc...

Fayedily的博客 286

骑砍Ⅱ霸主MOD开发(16)-FaceKey&BannerKey

摘要:本文介绍了FaceKey人物模型和BannerKey旗帜模型的生成流程。FaceKey通过序列化参数生成人物模型,包括头部(脸部、嘴、睫毛、眼睛)、眉毛、头发、身体和躯干等组件,每个部分通过特定标签和骨骼绑定实现。BannerKey则通过解析参数生成旗帜模型,包括模型、贴图和颜色等元素。两种模型都采用参数化设计和XML配置文件实现模型生成与定制。

骑砍战团&霸主MOD开发 2284

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

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

深度学习工具包 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]动态规划之Triangle

动态规划之Triangle题目思考答案 题目 leetcode入口 思考 刚开始想这道题,想着的是建立一维的表格。 但是到某一层的距离,不能用到前面层的距离表示。 查了网上答案, 看了在求每一层的最小距离的时候,需要求得到该层每一个格子的最短距离,最后求该层最小的值 因此每层都要叠加。 答案 class Solution { public: int minimumTotal(vector&...

crabstew的博客 230

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

LeetCode-Triangle

本文是LeetCode-Triangle的题解。

大汪的博客 245

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

【LeetCode】 Pascal's Triangle 系列

Pascal’s Triangle 118.Pascal's Triangle 119. Pascal's Triangle II

夏至亦韵 264

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,7], ...

LeeWei 218

Leetcode: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], [

littlebirdman的专栏 1595

leetcode之triangle(动态规划)

leetcode之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],...

此心光明,亦复何言~ 369

Pascal's Triangle - LeetCode

目录 题目链接 注意点 解法 小结 题目链接 Pascal's Triangle - LeetCode 注意点 就是杨辉三角形 有可能numRows等于0 解法 解法一:规律是每一行的首个和结尾一个数字都是1,从第三行开始,中间的每个数字都是上一行的左右两个数字之...

weixin_30642305的博客 132

leetcode笔记:Pascal's Triangle II

该题要求只输出第k行的元素值,并且要求空间复杂度为`O(k)`,因此,采用的方法是只使用一个定长的数组,用于存放每一行的元素值,对于每个新的行,可对原先存放的行从后往前扫描,主要分为以下三种情况: 最后一个元素,直接等于1; 对于下标为i的中间元素,有:`result[i] = result[i-1] + result[i]`; 第一个元素,直接等于1;

liyuefeilong的专栏 1298

[LeetCode]120. Triangle

[LeetCode]120. Triangle题目描述思路动归,新建一个状态保存数组 原数组 状态数组 2 2 3 4 5 6 6 5 7 11 10 13 4 1 8 3 15 11 18 16 所以结果是11代码class Solution { public: int minimumTotal(vector<vector<int>>& triangl

Lcharon的博客 292

【leetcode】【medium】120. Triangle​​​​​​​

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], ...

lemonade13的博客 100

LeetCode 120.Triangle【Java】

题目描述 LeetCode 120.Triangle AC代码 f[i][j]f[i][j]f[i][j]表示从起点走到第i行第j个元素的所有路径上的数的最小和。 从第i−1i-1i−1行到第iii行,有两种走法: 1.从右上角下来:f[i][j]=f[i−1][j]+nums[i][j]f[i][j]=f[i-1][j]+nums[i][j]f[i][j]=f[i−1][j]+nums[i][...

NayelyA的博客 212

leetcode:119. Pascal's Triangle II(Java)解答

转载请注明出处:z_zhaojun的博客 原文地址:http://blog.youkuaiyun.com/u012975705/ 题目地址:https://leetcode.com/problems/pascals-triangle-ii/ Pascal’s Triangle II Given an index k, return the kth row of the Pascal's tri

z_zhaojun的博客 2592
上一篇: LeetCode Recover Binary Search Tree
下一篇: LeetCode Add Two Numbers
FightForProgrammer
博客等级 码龄13年 239粉丝 75原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值