【LeetCode_112】路径总和(深度优先)

关于bfs(广度优先搜索算法)和dfs(深度优先搜索算法)--leetcode题:1036. 逃离大迷宫;112. 路径总和;113. 路径总和 II;102. 二叉树的层序遍历;200. 岛屿数量 leetcode 每日一题 1036. 逃离大迷宫 在一个 106 x 106 的网格中,每个网格上方格的坐标为 (x, y) 。 现在从源方格 source = [sx, sy] 开始出发,意图赶往目标方格 target = [tx, ty] 。数组 blocked 是封锁的方格列表,其中每个 blocked[i] = [xi, yi] 表示坐标为 (xi, yi) 的方格是禁止通行的。 每次移动,都可以走到网格中在四个方向上相邻的方格,只要该方格 不 在给出的封锁列表 blocked 上。同时,不允许走 阅读详情

题目描述:给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例:

给定如下二叉树,以及目标和 sum = 22,

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

代码:深度优先遍历二叉树,每深入一次,sum-根节点的值,当到达叶子节点的时候,判断sum是否等于当前的节点值,如果等于,说明找到了,否则尝试另外一条路径

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null) return false;
        if(root.left==null && root.right==null) return sum-root.val==0;
        return hasPathSum(root.left,sum-root.val)
        ||hasPathSum(root.right,sum-root.val);
    }
}

 

还在手敲LaTeX公式?用Rime小狼毫打造你的专属数学输入法(附完整配置包) 本文介绍如何利用Rime小狼毫输入法引擎打造专属数学公式输入方案,显著提升LaTeX公式输入效率。通过详细配置教程和智能补全技巧,帮助科研人员和学生实现3-5倍的输入速度提升,特别适合学术写作和技术文档创作场景。 阅读详情

相关推荐

手把手教你用TP4056和PMOS管搭建锂电池自动切换电路(含元器件选型指南)

本文详细介绍了如何使用TP4056和PMOS管搭建锂电池自动切换电路,包括核心架构设计、元器件选型指南和PCB布局优化。通过智能充电算法和电源路径切换模块,实现外部供电与锂电池的无缝切换,提升便携式设备的电源管理效率。

julia4scientist的博客 888

关于二叉树,你该了解这些!

我们要开启新的征程了,大家跟上!

代码随想录 922

国内合规开通ChatGPT Plus实操指南:银行卡绑卡与支付全解析

ChatGPT Plus 是 OpenAI 官方推出的高级订阅服务,基于 GPT-4o 多模态大模型提供语音交互、图像理解与长上下文处理能力。其核心使用前提在于完成合规的国际支付绑定,而非网络接入方式。技术原理上,OpenAI 采用 Stripe 支付网关进行风控校验,重点匹配银行跨境权限、卡片类型(仅支持 Visa/Mastercard/Amex 信用卡)、BIN 号段及地理位置一致性。该机制决定了95%的绑卡失败源于银行端配置缺失或卡片不兼容,而非网络问题。实际应用中,PayPal 作为中间支付层可显著

chuannaoxuan4674的博客 1954

Leetcode112. 路径总和

Every day a leetcode 题目来源:112. 路径总和 解法1:递归 hasPathSum 函数:询问是否存在从当前节点 root 到叶子节点的路径,满足其路径和为 sum。 假定从根节点到当前节点的值之和为 val,我们可以将这个大问题转化为一个小问题:是否存在从当前节点的子节点到叶子的路径,满足其路径和为 targetSum - val。 于是,这个问题可以用递归实现。 退出条件:走到了空结点 当遇到叶子节点时,判断该值是否等于剩余的targetSum。是,返回 true,不是返回 fa

ProgramNovice的博客 1471

海康VM加密狗无法识别常见问题排查

海康VM加密狗无法识别常见问题排查

视觉人机器视觉的博客 2710

MaxEnt软件的下载与安装

1、下载网站:http://lucky-boy.ys168.com/ (这是之前在网上搜到的,里面有许多软件安装包,感谢网页主的资源共享,违权必删)

weixin_42191203的博客 2万+

微软,Google面试题 (4) —— 在二叉树中找出和为某一值的所有路径

输入一颗二叉树,从根节点到叶子节点的所有节点构成一条路径,打印出和与输入整数相等的所有路径#include //思路很简单,遍历所有路径void getPath(struct treeNode* node, int sum, vector& stack, int currentSum) { //stack用来存放路径 if (node == NULL)

cesc 1530

【TC3xx芯片】TC3xx芯片STM介绍

TC3xx芯片STM介绍

qq_36056498的博客 2280

LeetCode 112. 路径总和

🌈🌈😄😄 欢迎来到茶色岛独家岛屿,本期将为大家揭晓LeetCode 112. 路径总和,做好准备了么,那么开始吧。 🌲🌲🐴🐴

weixin_62275996的博客 682

华为OD机试 - 魔法收积木 - 二进制(Java 新系统 200分)

华为OD机试 新系统 题库疯狂收录中,刷题。

学Java,找哪吒 442

OpenClaw赚钱实录:从“养龙虾“到可持续变现的实践指南

OpenClaw已经开源3个月有余,作为深耕AI Agent领域的博主,我亲身探索了各种基于OpenClaw的赚钱方法,也踩过坑、付出了时间与精力。现在,我将这些真金白银砸出来的实战经验,毫无保留地总结成这个专栏,分享给不想从零开始摸索的你。博主在优快云已有7万+粉丝和1100万+阅读量,但这却是我的第一个付费专栏。正因如此,我比任何人都更珍惜这个“第一次”。我会像一个手艺人打磨作品一样,死磕每一篇文章的质量,并持续根据订阅者的反馈优化内容。也许你的疑问就是当篇文章的优化点。

冯·诺依曼 2440

LeetCode-112. 路径总和(java)

金三银四,又到了刷题月。有时间的话,希望大家还是尽量刷起来咯。帮助往往不是直接体现出来的,但会让你对很多东西的底层实现了解的更深刻。

**My Coding Family** 1161

深度学习工具包 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 112. 路径总和:深度优先搜索的应用

路径总和问题是树算法中的经典问题,掌握它不仅有助于解决相关的LeetCode问题,也能帮助我们更好地理解深度优先搜索的思想。希望这篇文章对大家有所帮助,祝大家刷题愉快!

cannonjinx的博客 4270

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

leetcode112.路径总和/dfs

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。 说明: 叶子节点是指没有子节点的节点。 示例: 给定如下二叉树,以及目标和 sum = 22, 5 / \ 4 8 / / \ 11 13 4 ...

yyf_blog 316

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

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

(LeetCode 面试经典 150 题) 112. 路径总和 (深度优先搜索dfs)

【代码】(LeetCode 面试经典 150 题) 112. 路径总和 (深度优先搜索dfs)

记录一些刷过的题并分享学习心得 436

LeetCode 112. 路径总和(深度优先搜索dfs、二叉树)

【代码】LeetCode 112. 路径总和(深度优先搜索dfs、二叉树)

记录一些刷过的题并分享学习心得 296

迭代法(迭代+栈)模拟递归实现深度优先搜索(DFS):以力扣原题[112. 路径总和]及[113. 路径总和 II]为例

如果直接将 road 作为参数,因为是传引用,子递归对 road 的改变将直接影响上层递归中 road 的值(毕竟自始至终都是在对同一个对象做操作),如果要以用 road 做参数的方式实现回溯,需要在传递 road 时 new 一个新的对象,新对象即是子递归需要的新 road,将新对象作为参数传递给子递归函数,这样,每次递归调用时传入的 road 都不同,子递归对 road 的改变也就不会影响上层递归中 road 的值了。在状态转移中有一个深度优先搜索中重之又重的概念:回溯。

bluecyan的博客 998

LeetCode 112题:路径总和的DFS解法与优化技巧

深度优先搜索(DFS)是解决二叉树路径问题的经典算法,通过递归或迭代方式遍历所有可能路径。其核心原理是优先探索最深层节点,适用于需要完整路径搜索的场景如文件系统匹配、游戏决策树等。在LeetCode高频题路径总和中,DFS能以O(n)时间复杂度和O(h)空间复杂度高效解决问题。本文详解递归与迭代两种实现,特别介绍路径记录、提前终止等优化技巧,并拓展到路径总和II/III等变种题目。掌握这些算法模板可提升解决树形结构问题的能力,同时为工程实践中的依赖解析、网络爬虫等场景提供解决方案。

weixin_30561425的博客 371

力扣--深度优先算法112.路径总和

【代码】力扣--深度优先算法112.路径总和。

weixin_73865269的博客 240

LeetCode 112题:二叉树路径总和的DFS解法详解

深度优先搜索(DFS)是解决二叉树遍历问题的经典算法,特别适用于路径查找类问题。DFS通过递归或迭代方式系统地探索树结构,其核心原理是沿着分支深入到底再回溯。在算法面试中,路径总和问题考察了DFS的应用能力与边界条件处理技巧。实际工程中,类似算法可用于文件系统遍历、决策树分析等场景。本文以LeetCode 112题为例,详解如何通过DFS判断二叉树中是否存在特定和的路径,包含递归与迭代两种实现,并讨论负值节点处理等边界情况。掌握这类算法对提升树结构问题解决能力至关重要,也是应对大厂算法面试的基础技能。

weixin_34248705的博客 349

【力扣日记】112 路径总和 | 深度优先搜索 DFS

题目描述 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。 说明: 叶子节点是指没有子节点的节点。 算法思路 很简单,仅需要判断一条从根到叶的路径是否满足目标值。 采用递归的方式。结束条件是 if root.left==None and root.right==None:return sum - root.val == 0 完整算法: cl...

Heart_for_Ling的博客 462

leetcode112. 路径总和 & leetcode113. 路径总和II,图文并茂,教你完全弄懂DFS,附详细代码

leetcode112. 路径总和 & leetcode113. 路径总和II,图文并茂,教你完全弄懂DFS,附详细代码

热爱C++和golang的学生 2496

LeetCode112.路径总和

LeetCode112.路径总和 version 1 # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: ...

qq_42991793的博客 175

【LeetCode 112】 路径总和 (简单) DFS

题目: 代码: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int flag=0,num; v

黑桃 223

LeetCode112. 路径总和(DFS)

1、题目描述 https://leetcode-cn.com/problems/path-sum/ 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。说明: 叶子节点是指没有子节点的节点。 示例: 给定如下二叉树 [5,4,8,11,null,13,4,7,2,null,null,null,1],以及目标和 sum = 22 返回true, 因为存在目标和为 22 的根节点到叶子节点的路径5->4->11->2。...

IOT_victor的博客 281

[Tree Depth First Search] 路径总和

这个小分类:Tree Depth First Search(树上的DFS),更新深度优先搜索算法相关的题目 leetcode 112 ,路径总和,难度easy 0. 题干 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。 说明: 叶子节点是指没有子节点的节点。 示例: 给定如下二叉树,以及目标和 sum = 22, 返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。 1. 代码 /**

编程菜汝狗 251
上一篇: 【LeetCode_171】数字字符:Excel表列序号
下一篇: 【LeetCode_160】相交链表:快慢指针
West Money
博客等级 码龄9年 7粉丝 48原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值