zoukankan      html  css  js  c++  java
  • leetcode——113. 路径总和 II

    同看懂做不出来。。。

    class Solution:
        def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
            res=[]
            if not root:
                return []
            def helper(root,sum,tmp):
                if not root:
                    return
                if not root.left and not root.right and sum-root.val==0:
                    tmp+=[root.val]
                    res.append(tmp)
                    return 
                helper(root.left,sum-root.val,tmp+[root.val])
                helper(root.right,sum-root.val,tmp+[root.val])
            helper(root,sum,[])
            return res
    执行用时 :72 ms, 在所有 python3 提交中击败了39.94%的用户
    内存消耗 :19.1 MB, 在所有 python3 提交中击败了5.08%的用户
     
    ——2019.11.21
     

    复习:
    public List<List<Integer>> pathSum(TreeNode root, int sum) { //得用到栈吧
            //遍历所有路径
            List<List<Integer>> list = new ArrayList<>();
            if(root == null){
                return list;
            }
            Stack<Integer> path = new Stack<>();
            pathSum(root,sum,list,path);
            return list;
        }
    
        private void pathSum(TreeNode node, int sum, List<List<Integer>> list,Stack<Integer> path) {
            if(node == null && sum != 0){
                return;
            }
            if(node != null) {
                if (node.left == null && node.right == null && sum == node.val) {
                    path.push(node.val);
                    list.add(new ArrayList<>(path));
                    path.pop();
                } else {
                    path.push(node.val);
                    pathSum(node.left, sum - node.val, list, path);
                    pathSum(node.right, sum - node.val, list, path);
                    path.pop();
                }
            }
        }

    ——2020.7.2

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    实战篇之实现 OutLook 中以 EDM 形式发送通知邮件
    ASP.NET MVC5 之路由器
    ASP.NET MVC5 之数据迁移
    说不出的烦
    ASP.NET MVC5 之 Log4Net 的学习和使用
    读取配置文件参数和文件路径
    序列化和反序列化示例
    面向对象之封装
    面向对象4之常用的乱七八糟
    面向对象三之继承和派生
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11907986.html
Copyright © 2011-2022 走看看