Update 0797.所有可能的路径.md

添加Python实现
This commit is contained in:
Asterisk
2022-09-09 12:42:55 -04:00
committed by GitHub
parent 53994bcde0
commit bd2832ec6a

View File

@ -296,5 +296,29 @@ public:
### Java
### Python
```
class Solution:
def __init__(self):
self.result = []
self.path = [0]
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
if not graph: return []
self.dfs(graph, 0)
return self.result
def dfs(self, graph, root: int):
if root == len(graph) - 1: # 成功找到一条路径时
# ***Python的list是mutable类型***
# ***回溯中必须使用Deep Copy***
self.result.append(self.path[:])
return
for node in graph[root]: # 遍历节点n的所有后序节点
self.path.append(node)
self.dfs(graph, node)
self.path.pop() # 回溯
```
### Go