AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

LeetCode 437. Path Sum III    原题链接    简单

作者: 作者的头像   邓泽军 ,  2019-09-13 23:08:19 ,  所有人可见 ,  阅读 1296


2


题目描述

从任意起点,找一条连续的路径,使得和为sum。

思路:

1.可以遍历每一条路径,在遍历的过程中,如果和为sum,那么res++
2.再依次删除这条路径之前加入的节点,如果和为sum,那么res ++。

C++ 代码

/**
 * 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 pathSum(TreeNode* root, int sum) {
        int res = 0;
        vector<TreeNode*> out;
        helper(root, sum, 0, out, res);
        return res;
    }
    void helper(TreeNode* node, int sum, int curSum, vector<TreeNode*>&out, int &res) {
        if (!node) return ;
        curSum += node->val;
        out.push_back(node);
        if (sum == curSum) res ++;
        int t = curSum;
        for (int i = 0; i < out.size() - 1; i ++) {// out,保存的当前路径,依次去掉路径中的点。
            t -= out[i]->val;
            if (t == sum) res ++;
        }
        helper(node->left, sum, curSum, out, res);
        helper(node->right, sum, curSum, out, res);
        out.pop_back();
    }
};

1 评论


用户头像
alin   2020-04-20 21:44         踩      回复

楼主你好,想请问你最后递归函数里面为什么 要out.pop_back()


App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息