leetcode 112/113( Path Sum (II)路径求和)

LIGGGHTS颗粒模拟入门:从DEM原理到工程实践 离散元法(DEM)是一种用于模拟颗粒物质行为的数值方法,其核心原理是通过计算每个颗粒的运动和相互作用来预测颗粒系统的宏观行为。该方法基于牛顿第二定律和接触力学模型,能够精确描述颗粒间的碰撞、摩擦和粘结等微观机制。在工程实践中,DEM技术为优化工业设备设计、预测材料流动和减少实验成本提供了重要价值。它广泛应用于制药造粒、矿石破碎、粉体输送和农业加工等领域,帮助工程师和研究人员深入理解颗粒系统的复杂动力学。LIGGGHTS作为一款基于LAMMPS的开源DEM软件,继承了其高效的并行计算架构,并针对颗粒模拟进行了 阅读详情

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \      \
7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

思路:
DFS,可以用中序遍历,逐个减去访问的节点值,比较时可以用sum-root.val的方式逐个减掉元素,最后只剩下当前节点值=当前sum即可

    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null) {
            return false;
        }
        
        if(root.left == null && root.right == null && root.val == sum) {
            return true;
        }
        
        return(hasPathSum(root.left, sum - root.val) || 
               hasPathSum(root.right, sum - root.val));
    }

和112类似,只是这次要输出所有满足条件的path
Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

Return:

[
[5,4,11,2],
[5,8,4,5]
]

思路:
仍然采用112的逐个用sum-访问节点值的方法,只是这次要访问所有path,不能用112的return left || right, 而是都要访问,然后需要用一个Stack保存访问节点的值,访问完它的左右子树后pop掉这个值

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        Stack<Integer> stack = new Stack<>();
        
        dfs(root, sum, stack, result);
        return result;
    }
    
    public void dfs(TreeNode root, int sum, Stack<Integer> stack, 
                   List<List<Integer>> result) {
        if(root == null) {
            return;
        }
        
        stack.push(root.val);
        
        if(root.left == null && root.right == null && root.val == sum) {
            ArrayList<Integer> tmp = new ArrayList<Integer>(stack);
            result.add(tmp);
            stack.pop();
            return;
        }
        
        dfs(root.left, sum - root.val, stack, result);
        dfs(root.right, sum - root.val, stack, result);
        
        stack.pop();
    }
【学习笔记】计算机网络 第八章 无线局域网(WLAN) 计算机网络 第八章 无线局域网(WLAN) 阅读详情

相关推荐

在QTableWidget中添加支持多选的QComboBox并显示

定义自定义表格项,主要用于显示复选框自定义的多选ComboBox类自定义委托类,用于表格中的多选ComboBox代码展示如下。

YUyang0304的博客 2781

leetcode解题之112 & 113 & 437. Path Sum java版(二叉树路径和)

112. Path Sum ,113. Path Sum II,437. Path Sum III, leetcode解题之112 & 113 & 437. Path Sum java版(二叉树路径和)

mine_song的博客 1114

uniCloud云存储进阶:七牛云扩展存储从开通、绑定域名到批量上传的完整实战

本文详细介绍了uniCloud云存储进阶实践,重点讲解如何通过七牛云扩展存储实现从开通、绑定域名到批量上传的完整流程。内容涵盖成本优势分析、域名备案方案、SSL证书配置、多文件并发上传控制等实战技巧,并提供可直接复用的代码示例,帮助开发者高效构建内容社区类应用。

weixin_26985923的博客 468

leetcode 112. Path Sum, 113. Path Sum II | 112,113. 路径总和 I, II(Java)

题目 https://leetcode.com/problems/path-sum/ https://leetcode.com/problems/path-sum-ii/ 题解 简单的遍历二叉树,不解释,直接上代码 112. Path Sum /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; *

寒泉 4万+

DDPG算法实战:用Python一步步实现深度强化学习中的连续动作控制

本文详细介绍了DDPG算法在深度强化学习中的连续动作控制应用,通过Python和PyTorch实现从零构建智能体。内容涵盖环境搭建、网络架构设计、经验回放、OU噪声实现及训练流程优化,帮助开发者掌握DDPG在机械臂控制等场景的核心技术。

weixin_30335575的博客 415

[c语言]用辗转相除法求最大公约数,递归和不递归两种

在c语言的学习中必然会遇到求两个数之间的最大公约数的题目,那么对于其他经典方法,最简便快捷的方式就是利用辗转相除法 辗转相除法又叫做欧几里得算法,目的是为了求两个正整数的最大公约数 定理:gcd(a,b) = gcd(b ,a%b) //在这里用(a,b)表示a和b的最大公约数证明:a可以表示成a = kb + r,则r = a %b 假设d是a,b的一个公约数,则有 d|a, d|b,而r = a - kb,因此d|r //这里的"|"的意思是 :d是b的因数 ,d是a的因数 因此d...

ZZRBlogger的博客 1万+

[Java]LeetCode 112Path Sum&113Path Sum II

[Java]LeetCode 112Path Sum&113Path Sum II

fumier的专栏 513

如何用python自己复现worldquant brain中的回测结果

本文介绍了在Python中复现WorldQuant Brain平台上alpha 101因子1和4的回测框架构建要点。重点分析了Brain平台的策略设置:使用TOP 3000高流动性股票(可用中证1000/2000替代);delay=1表示t日信号在t+1日开盘调仓;详细解释了market/sector/industry/subindustry四级中性化方法;说明了decay参数控制持仓权重线性衰减;以及TRUNCATION参数限制单股仓位风险。文章还探讨了不同调仓时点的实现差异,为自主构建量化回测系统提供了

夏之微风的博客 731

Leetcode 113. Path Sum II 路径和2 解题报告

1 解题思想这道题和Leetcode 112是同宗的,112只要求输出是否存在一个Case,而这题要求输出所有Case的路径。 方法基本是一样他,遍历到底的时候保存一下路径就好Leetcode 112. Path Sum 路径和 解题报告 2 原题Given a binary tree and a sum, find all root-to-leaf paths where each path's

MebiuW的专栏 2189

材料仿真软件:LAMMPS_(8).温度和压力控制

在 LAMMPS 中,温度和压力的控制是通过多种恒温器和恒压器实现的。Nose-Hoover 恒温器和恒压器因其准确性和广泛适用性而被经常使用,而 Berendsen 恒温器和恒压器则因其计算效率高而适用于初步仿真或粗粒化模型。温度重标和压力重标方法虽然简单,但在某些情况下可以快速调整系统的温度和压力。通过选择合适的控制方法,可以根据具体的需求和系统特性来设计和运行分子动力学仿真,从而获得准确和可靠的结果。在实际应用中,建议先进行初步的仿真以确定合适的控制参数,然后再进行细致的仿真以验证结果的稳定性。

kkchenjj的博客 1692

DeiT详解:知识蒸馏的Transformer

DeiT模型(8600万参数)仅用一台 GPU 服务器在 53 hours train,20 hours finetune,仅使用 ImageNet 就达到了 84.2 top-1 准确性,而无需使用任何外部数据进行训练,性能与最先进的卷积神经网络(CNN)可以抗衡。其核心是提出了针对 ViT 的教师-学生蒸馏训练策略,并提出了方法,使得在视觉领域训练得又快又好。

走在深度学习前沿的小宋 2636

Leetcode113. 路径总和 Path Sum II(Java)

Leetcode113. 路径总和 Path Sum II(Java) ##Tree##, ##Depth-first Search## 路径总和II 参考Leetcode112路径总和,用回溯法 因为需要找到所有路径,因此需要DFS整棵子树 dfs(TreeNode root, int sum)表示找到所有从root出发,到叶节点和为sum的路径的函数 递归遍历左右儿子结点,以左儿子结点为例dfs(root.left, sum - root.val)表示找到所有从root.left出发,到叶子节点和为s

qq_42411921的博客 206

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

leetcode 112. Path Sum 、 113. Path Sum II 、437. Path Sum III

112. Path Sum 自己的一个错误写法: class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if(root == NULL) return false; int value = 0; return hasP...

weixin_30849403的博客 114

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

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

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

[JavaScript 刷题] 树 - Path Sum I & II, leetcode 112 & 113

github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。题目地址:112. Path Sum如下:这题解决思路还挺直接的,只需要在到达 leaf 结点时检查一下当前的 targetSum 是否为当前结点的值即可。不使用 是因为有一个边界条件:,一个空的节点不管 targetSum 是什么,都应该是 false。但是如果用上面这个边界条件就会导致当传进去的节点为空时,这成了一个可以通过的 cas

GoldenaArcher的博客 530

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Leetcode 113 Path Sum II(递归)

题目连接:Leetcode 113 Path Sum II解题思路:与 Leetcode 112 类似,搜索过程中记录路径并且在ans中保存可行方案。/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right;...

不慌不忙、不急不躁 287

【一天一道LeetCode】#113. Path Sum II

一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given

ZeeCoder 2659

Path Sum (路径和)----(LeetCode112+LeetCode113+LeetCode437)

Leetcode 112 Path Sum Leetcode 113 Path Sum II Leetcode 437 Path Sum III

rainMan的博客 741

LeetCode 112+113+437. Path Sum

题目要求: Example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 return true, as there exist a root-to-leaf path 5->4->11-&...

肉丸不肉 433

【LeetCode】113. Path Sum II 解题报告(Python)

题目分析: 给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。说明: 叶子节点是指没有子节点的节点。 示例:给定如下二叉树,以及目标和 sum = 22, 返回: [[5,4,11,2],[5,8,4,5]] 解题思路: 这一题是【LeetCode】112. Path Sum的进阶版,比上一题要稍微难一些,但是用上一题的思路可以解决。 如果根节点为空,直接返回...

L141210113的专栏 378

[Leetcode] Path Sum I,II,III

112. Path Sum I: 点击打开链接 /** * Definition for a binary tree node. //判断是否有这样的路径满足和为sum * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(i

offerkkl的博客 435

第三周:( LeetCode 112 113 ) Path Sum I II(c++)

最近这一周进入了图的分解相关算法的学习,由于这方面以前做题的经验不多,因此每种算法应该会多做几道题,从最简单的dfs开始,本博文选的两道题:leetcode112、113,正是基于图(二叉树)的深度优先遍历的题。113比112多了一个保存路径的步骤,实际上差别不是特别大!

marlonlyh的博客 361

Leetcode 112 path sum & 113 path sum 2

Leetcode 112 path sum & 113 path sum 2 给定一棵二叉树和一个整数。path sum 要求判断在该二叉树中是否存在一条根节点到叶子结点的路径,路径上的数字和等于给出的整数。path sum 2要求返回所有满足的路径。 算法遍历整棵二叉树,在遍历的同时,若向子代走,则将节点值加起来,若回溯,则减掉节点值。对于path sum,在每个叶子结点处进行判断当前和是否

SSDirector的博客 382

LeetCode113—Path Sum II

LeetCode113—Path Sum II

上善若水 378

LeetCode 113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum. the follow up the LC112. but the difference is: LC112 ask if we can find some path like that then return true. and this problem needs us to return all th

Tech in Pieces 298

leetcode【113】 Path Sum II【c++,递归和非递归】

问题描述: Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. Note:A leaf is a node with no children. Example: Given the below binary tree andsum =...

fanyuwgy的博客 218

LeetCode113.Path Sum II Python实现(详细解析以及错误展示分析)

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum. Note: A leaf is a node with no children. Example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ /

qq_41704019的博客 361
上一篇: leetcode 515. Find Largest Value in Each Tree Row(二叉树每层的最大值)
下一篇: 547. Friend Circles(朋友圈)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值