首页 > 其他分享 >113.path-sum-ii 路径总和 II

113.path-sum-ii 路径总和 II

时间:2022-09-02 10:45:30浏览次数:68  
标签:ii res sum II vector targetSum path root

#include <vector>
using std::vector;
class Solution {
  private:
    void get_sum(TreeNode *root, vector<int> path, int sum, vector<vector<int>> &res, int targetSum) {
        sum += root->val;//回溯被隐藏起来了
        path.push_back(root->val);//回溯被隐藏起来了,因为函数里的path改变了,没有改变函数外的path
        if (root->left == nullptr && root->right == nullptr) {
            if (sum == targetSum) {
                res.push_back(path);
                return;
            }
            else
                return;    
        }
        if (root->left != nullptr) 
            get_sum(root->left, path, sum, res, targetSum);
        if (root->right != nullptr)
            get_sum(root->right, path, sum, res, targetSum);
        return;
    }
  public:
    vector<vector<int>> pathSum(TreeNode *root, int targetSum) {
        vector<vector<int>> res;
        vector<int> path;
        if (root == nullptr)
            return res;
        get_sum(root, path, 0, res, targetSum);
        return res;
    }
};

标签:ii,res,sum,II,vector,targetSum,path,root
From: https://www.cnblogs.com/zwyyy456/p/16648990.html

相关文章

  • Geopandas III (Kafka-Stream)
    GeopandasIII(Kafka-Stream)大家好,在本文中,我们将使用geopandas和matplotlib以及来自kafka的数据制作如下实时地图。文章中使用的代码和数据关联您可以通过访......
  • The 2022 Hangzhou Normal U Summer Trials
    A.Hello,ACMer!这题就是找到hznu的个数#include<bits/stdc++.h>usingnamespacestd;int32_tmain(){strings;cin>>s;intcnt=0;for(i......
  • IIC协议介绍
    讲解I2C协议之前,首先列出GPIO的输出模式配置图,输出模式有推挽输出、开漏输出。推挽输出:可以输出高、低电平,连接数字器件。推挽结果一般是指两个三极管分别受两互补信号的......
  • 112.path-sum 路径总和
    带明显的回溯的版本#include<vector>usingstd::vector;classSolution{private:vector<int>res;intsum=0;public:voidcnt_sum(TreeNode......
  • 在博客园的博客文章中自动播放 asciinema
    需求我的文章中都是用Markdown写的,所以嵌入的asciinema只能通过Embedimagelink的方式,这就导致打开文章页面后只有一个asciinema的预览图,点击图片后会跳转到asc......
  • sumbs项目搭建
    在dao下新建BaseDao类用于读取上面的数据库配置文件点击查看代码importjava.io.IOException;importjava.io.InputStream;importjava.sql.*;importjava.util.Prop......
  • [Google] LeetCode 552 Student Attendance Record II
    Anattendancerecordforastudentcanberepresentedasastringwhereeachcharactersignifieswhetherthestudentwasabsent,late,orpresentonthatday.......
  • 算法 - 螺旋矩阵 II
    59.螺旋矩阵II这道题困扰了我很久,一些边界值控制比较繁琐,但是偶然发现按照以下方法写,在Leetcode可以AC。classSolution{publicstaticint[][]generateMatrix(......
  • [LeetCode] 1315. Sum of Nodes with Even-Valued Grandparent 祖父节点值为偶数的节
    Giventhe root ofabinarytree,return thesumofvaluesofnodeswithan even-valuedgrandparent.Iftherearenonodeswithan even-valuedgrandparent......
  • SP1557 GSS2 - Can you answer these queries II
    SP1557GSS2-CanyouanswerthesequeriesII题目大意给出\(n\)个数,\(q\)次询问,求最大子段和,相同的数只算一次。分析看到一个区间内相同的数只能算一次,经验告诉......