mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #1638 from casnz1601/patch-25
Update 0797.所有可能的路径.md
This commit is contained in:
@ -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
|
||||
|
Reference in New Issue
Block a user