Leetcode437. 路径总和 III(HOT100)

链接

我的代码:

cpp 复制代码
class Solution {
public:
    int res = 0;
    int pathSum(TreeNode* root, int targetSum) {
        if(!root)return 0;
        dfs(root,targetSum);
        pathSum(root->left,targetSum);
        pathSum(root->right,targetSum);
        return res;
    }
    void dfs(TreeNode*root,long long targetSum){
        if(!root)return;
        targetSum-=root->val;
        if(targetSum==0){
            res++;
        }
        dfs(root->left,targetSum);
        dfs(root->right,targetSum);

    }
};

更好的代码:

cpp 复制代码
class Solution {
public:
    unordered_map<long long,int> cnt;
    int res = 0;
    int pathSum(TreeNode* root, int targetSum) {
        cnt[0] = 1;
        dfs(root,targetSum,0);
        return res;
    }
    void dfs(TreeNode*root,int targetSum,long long cur){
        if(!root)return;
        cur+=root->val;
        res+=cnt[cur-targetSum];
        cnt[cur]++;
        dfs(root->left,targetSum,cur),dfs(root->right,targetSum,cur);
        cnt[cur]--;
    }
};

第二次这个代码刚开始写的时候:没有把cnt中key的类型从int改为long long,然后一直疑惑:dfs形参cur的类型就是int啊...........

原来cnt的key的类型也要改,因为cnt存储的是某和出现了多少次,这个和可能会溢出。

相关推荐
格林威4 小时前
常规线扫描镜头有哪些类型?能做什么?
人工智能·深度学习·数码相机·算法·计算机视觉·视觉检测·工业镜头
程序员莫小特6 小时前
老题新解|大整数加法
数据结构·c++·算法
过往入尘土8 小时前
服务端与客户端的简单链接
人工智能·python·算法·pycharm·大模型
zycoder.8 小时前
力扣面试经典150题day1第一题(lc88),第二题(lc27)
算法·leetcode·面试
蒙奇D索大8 小时前
【数据结构】考研数据结构核心考点:二叉排序树(BST)全方位详解与代码实现
数据结构·笔记·学习·考研·算法·改行学it
智驱力人工智能9 小时前
工厂抽烟检测系统 智能化安全管控新方案 加油站吸烟检测技术 吸烟行为智能监测
人工智能·算法·安全·边缘计算·抽烟检测算法·工厂抽烟检测系统·吸烟监测
程序员爱钓鱼9 小时前
Go语言实战案例——进阶与部署篇:编写Makefile自动构建Go项目
后端·算法·go
_Power_Y9 小时前
Java面试常用算法api速刷
java·算法·面试
艾醒(AiXing-w)10 小时前
大模型面试题剖析:模型微调中冷启动与热启动的概念、阶段与实例解析
人工智能·深度学习·算法·语言模型·自然语言处理
天选之女wow10 小时前
【代码随想录算法训练营——Day32】动态规划——509.斐波那契数、70.爬楼梯、746.使用最小花费爬楼梯
算法·leetcode·动态规划