【LeetCode热题100(47/100)】路径总和 III

题目地址: 链接

思路: 通过前缀和 + 回溯,每次记录当前前缀和,每次记录当前离 targetSum 的偏移量, 统计当前满足条件的路径数量。

js 复制代码
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {number}
 */
var pathSum = function(root, targetSum) {
    let map = new Map();
    let ans = 0;
    function dfs(root, pre) {
        if(!root) return null;
        
        let ppre = pre + root.val;
        let check_num = ppre - targetSum; // 偏移量

        ans += map.get(check_num) || 0;
        map.set(ppre, map.get(ppre) + 1 || 1);

        dfs(root.left, ppre);
        dfs(root.right,ppre);
        map.set(ppre, map.get(ppre) - 1);
    }
    map.set(0, 1);
    dfs(root, 0);
    return ans;
};
相关推荐
Xの哲學1 小时前
Linux流量控制: 内核队列的深度剖析
linux·服务器·算法·架构·边缘计算
yaoh.wang1 小时前
力扣(LeetCode) 88: 合并两个有序数组 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·双指针
LYFlied2 小时前
【每日算法】 LeetCode 56. 合并区间
前端·算法·leetcode·面试·职场和发展
艾醒2 小时前
大模型原理剖析——多头潜在注意力 (MLA) 详解
算法
艾醒2 小时前
大模型原理剖析——DeepSeek-V3深度解析:671B参数MoE大模型的技术突破与实践
算法
jifengzhiling3 小时前
零极点对消:原理、作用与风险
人工智能·算法
鲨莎分不晴4 小时前
【前沿技术】Offline RL 全解:当强化学习失去“试错”的权利
人工智能·算法·机器学习
XFF不秃头5 小时前
力扣刷题笔记-全排列
c++·笔记·算法·leetcode
菜鸟233号5 小时前
力扣669 修剪二叉搜索树 java实现
java·数据结构·算法·leetcode