LeetCode 112. Path Sum

Sony微单相机alpha6000 wifi远程控制(1) 引言 Sony’s Camera Remote API beta SDK allows you to control a number of Sony cameras, including Sony Action cams, Sony Alpha cameras and Lens Style cameras, wirelessly from another device. 索尼于2017年三月Re... 阅读详情

LeetCode 112. Path Sum

Solution1:我的答案
递归写的好麻烦啊

/**
 * 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:
    bool hasPathSum(TreeNode* root, int sum) {
        if (!root)
            return false;
        else
            return my_hasPathSum(root, sum);
    }

    bool my_hasPathSum(TreeNode* root, int sum) {
        if (!root->left && !root->right) {
            if (sum - root->val == 0)
                return true;
            else
                return false;
        }
        else if (root->left && !root->right) 
            return my_hasPathSum(root->left, sum - root->val); 
        else if (!root->left && root->right)
            return my_hasPathSum(root->right, sum - root->val);
        else
            return my_hasPathSum(root->left, sum - root->val) 
                || my_hasPathSum(root->right, sum - root->val);
    }
};

Solution2:
简练的递归写法
参考网址:http://www.cnblogs.com/grandyang/p/4036961.html

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool 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);
    }
};
产品经理必备知识——API接口 在古代,我们的传输信息的方式有很多,比如写信、飞鸽传书,以及在战争中使用的烽烟,才有了著名的烽火戏诸侯,但这些方式传输信息的效率终究还是无法满足高速发展的社会需要。如果你选择允许,app就会根据你的当前位置为你提供更加个性化的一些服务,当然也有一些app拿到你的位置信息做出损害用户利益的行为,所以还是需要谨慎授权。首先,看接口文档的场景一般是自身业务模块需要获取外部的数据,但又不想自己重新开发,寻找外部已经实现的有开放能力的供应商(包含企业内部的)。通过发送请求和响应消息的方式实现程序间的通信。 阅读详情

相关推荐

西门子1200PLC编程实战:OB、FC、FB与DB的深度解析与应用技巧

本文深度解析西门子1200PLC编程中OB、FC、FB与DB四大核心功能块的应用技巧。通过工厂化比喻,阐明OB作为程序总调度、FC作为可重用函数、FB作为带记忆的智能设备以及DB作为数据仓库的角色与关系,并提供实战技巧,帮助工程师构建结构清晰、易于维护的高效PLC程序。

weixin_29280657的博客 444

Project Euler:Problem 81 Path sum: two ways

In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427. ⎛⎝⎜⎜⎜⎜⎜⎜1312016305

312小公举的专栏 859

SAP Workflow 工作流开发步骤总结

SAP WORKFLOW

qq_36952606的博客 5096

Project Euler 81:Path sum: two ways 路径和:两个方向

Path sum: two ways In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427.   ...

weixin_33834628的博客 176

tcllib2.0 package - csv

tcl lib 的csv库

shin 861

贝塞尔曲线基础

贝塞尔曲线于1962年由法国工程师皮埃尔·贝塞尔(Pierre Bézier)所广泛发表,他运用贝塞尔曲线来为汽车的主体进行设计。贝塞尔曲线最初由Paul de Casteljau于1959年运用de Casteljau演算法开发,以稳定数值的方法求出贝兹曲线。

YiYeZhiNian的博客 2053

SpringBoot云租车平台架构设计与实战

微服务架构下的汽车租赁系统开发涉及分布式事务、状态机设计等核心技术。通过SpringBoot+Vue技术栈实现B/S架构,采用策略模式处理动态计价规则,利用Redis分布式锁解决高并发场景下的资源竞争问题。典型应用场景包括车辆状态管理、订单分时计价等业务模块,其中状态机模式有效管理了车辆生命周期,而阿里云ECS+RDS的云原生部署方案则提供了弹性扩展能力。本文详解的云租车平台实现方案,为传统租车行业数字化转型提供了可复用的技术框架。

weixin_34146805的博客 280

自动化测试软件设计:C# + VISA 库实现多接口(GPIB/USB)测试仪器控制

本文介绍了如何利用C#和VISA库开发支持多接口的自动化测试软件。VISA库作为标准化API,能够统一控制GPIB、USB等不同接口的测试设备。文章详细阐述了软件设计目标,包括多接口支持、统一控制、自动化脚本执行等功能。重点讲解了C#中VISA库的安装配置,并提供了设备控制类的核心代码实现,涵盖设备连接、命令发送、响应读取等关键操作。通过具体示例展示了GPIB和USB设备的连接方式,并扩展了自动化测试脚本功能。该方案具有高扩展性和维护性,适用于电子设备测试、生产线检测等多种场景,为自动化测试系统开发提供了实

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 1716

【Leetcode】112. Path Sum 解题报告

给定sum ,求是否存在根节点到叶子节点的路径使路径上的节点和等于sum 方法1 递归 class Solution1: def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ ...

很吵请安静 362

PostgreSQL 在 Windows操作系统 无管理员权限情况下的部署详解

但是因为使用默认5432端口,我们修改了端口,所以连接报错,需要修改local连接信息,右键-属性修改相应信息即可,方式同上。(也别太任意吧,个人习惯工具放在不包含中文及特殊字符的目录,另外目录名尽量简短,避免不必要的麻烦)图中我解压到了自己的tools\postgresql18。1)如果想修改默认的5432端口,找到初始化目录中的(上面的tools\postgresql18\。此处替换成你的实际目录\tools\postgresql18\pgsql\pgAdmin 4\runtime。

dong_zhi2328的博客 1120

2026华为OD机试真题 9月27日 新系统 【均衡调度】

华为OD机试真题 新系统 9月27号【均衡调度】,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试真题 【均衡调度】多语言题解。

qq_45776114的博客 1776

Project Euler:Problem 83 Path sum: four ways

In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by moving left, right, up, and down, is indicated in bold red and is equal to 2297. ⎛⎝⎜⎜⎜⎜⎜⎜1312016305378

312小公举的专栏 1119

13、深入理解 Microsoft 365 的安全与合规概念

本文深入探讨了 Microsoft 365 的安全与合规概念,涵盖文档存储、文件共享、审计、保留、eDiscovery、分类和保护以及网络等多个关键方面。通过合理配置这些功能,组织可以更好地管理和保护其数据资源,满足法规要求,并提升工作效率。文章还提供了最佳实践建议及流程图,帮助读者全面理解 Microsoft 365 的安全架构和管理策略。

k8s6orchestrator的博客 212

Leetcode 112 Path Sum(递归)

题目连接:Leetcode 112 Path Sum解题思路:递归,每次减掉当前结点的值,到叶子结点是,值为零为可行路径。/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNo...

不慌不忙、不急不躁 329

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

廖雪峰Python教程[完整版]

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

leetcode-112. Path Sum

leetcode-112. Path Sum题目: 典型的DFS。 迭代的终止条件:当前节点的值等于剩余的值,并且该节点为叶子节点 迭代过程:左右子节点结果相或

千念飞羽的专栏 744

深度学习工具包 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. Path Sum

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.For example:Given the below binary tree and sum = 22...

LeeWei 223

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

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

[LeetCode]112. Path Sum

[LeetCode]112. Path Sum题目描述思路递归,计算每条路径的和,当前节点为叶子节点时,比较当前和与目标和 PS: 写成目标和减去节点值的方式,可以简化代码代码#include <iostream>using namespace std;struct TreeNode { int val; TreeNode* left; TreeNode* right;

Lcharon的博客 323

LeetCode: 112. Path Sum

LeetCode: 112. Path Sum 题目描述 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. For example: Given...

杨领well的专栏 672

[勇者闯LeetCode] 112. Path Sum

[勇者闯LeetCode] 112. Path SumDescription 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. For ex

fanguzhai的博客 353

[leetcode]112. Path Sum

[leetcode]112. Path Sum Analysis 新的一天新的刷题,中午吃什么比较好呢—— [好想好想吃冰淇淋啊~] 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 p...

weixin_32135877的博客 129

LeetCode力扣 112. 路径总和 Path Sum 题解代码 JavaScript

问题https://leetcode-cn.com/problems/path-sum/ 练习使用JavaScript解答 /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @param {number} s.

Coding home - 漂流瓶jz 474

Leetcode-112. Path Sum

Leetcode-112. Path Sum

Eistert 223

leetcode 112. Path Sum

TreeInclude.h:测试用#ifndef _TREE_INCLUDE_H_ #define _TREE_INCLUDE_H_#include <iostream> #include <vector> #include <algorithm> #include <string>using namespace std;// 节点数据结构 struct TreeNode { int va

编码之路 280

Leetcode 笔记 112 - Path Sum

题目链接:Path Sum | LeetCode OJ 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. For example: Given the ...

weixin_30641999的博客 96

Leetcode 112. Path Sum (Easy) (cpp)

Leetcode 112. Path Sum (Easy) (cpp)

还是需要多学习!闷声大发财,这是坠吼的! 642

[LeetCode]112.Path Sum

【题目】 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. For example:Given the...

weixin_34248487的博客 79
上一篇: 【链表递归构造二叉树】LeetCode 109. Convert Sorted List to Binary Search Tree
下一篇: LeetCode 113. Path Sum II
Allenlzcoder
博客等级 码龄10年 925粉丝 512原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值