【Leetcode】【python】Path Sum II
来源:互联网 发布:电力代维软件 编辑:程序博客网 时间:2024/05/21 01:56
题目大意
将根到叶子的路径和为sum的路径都枚举出来。
解题思路
递归,并且用了python函数嵌套,有关函数嵌套可以看这一篇文章
其实一开始不想项标准答案一样用函数嵌套,毕竟别的语言可能不支持,以后看答案不方便,但是如果把list_all放在全局,需要每轮都去清空它,而leetcode跑测试的时候应该是一个类的对象跑完所有测试,所以全局变量会累加,只能按照标准答案写了。
注意:
嵌套的函数不需要再写self
内层函数可以访问外层函数中定义的变量,但不能重新赋值(rebind)
代码
class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ def dfs(root, cur_sum, list_temp): # 不需要self if root.left == None and root.right == None: if cur_sum == sum: return list_all.append(list_temp) if root.left: dfs(root.left, cur_sum + root.left.val, list_temp + [root.left.val]) if root.right: dfs(root.right, cur_sum + root.right.val, list_temp + [root.right.val]) if root == None: return [] list_all = [] dfs(root, root.val, [root.val]) return list_all
总结
阅读全文
0 0
- 【Leetcode】【python】Path Sum II
- 【LeetCode with Python】 Path Sum II
- 【leetCode】Path Sum II python实现
- Leetcode path-sum-ii Python Java
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- [LeetCode] Path Sum II
- 【leetcode】Path Sum II
- [LeetCode]Path Sum II
- [Leetcode]Path Sum II
- [leetcode]Path Sum II
- Leetcode: Path Sum II
- LeetCode-Path Sum II
- [leetcode] Path Sum II
- LeetCode - Path Sum II
- [LeetCode] Path Sum II
- JAVA企业面试题精选 Web基础 1-10
- 匈牙利算法模板 二分图最大匹配
- 深度学习与神经网络
- stud-2779裸bfs
- 《零基础入门学习Python》学习过程笔记【38类的继承】
- 【Leetcode】【python】Path Sum II
- POJ 3692 Kindergarten
- 一行代码解决各种IE兼容问题,IE6,IE7,IE8,IE9,IE10
- inux 安装虚拟机VMware-Workstation需要权限
- 在Linux下安装PHP过程中,编译时出现configure: error: libjpeg.(a|so) not found 错误的解决办法
- 常用 Git 命令清单
- web方向学习清单
- linux 下安装tomcat
- Git常用命令