From bd2832ec6a2cdcf43d292a661957327c069140d0 Mon Sep 17 00:00:00 2001 From: Asterisk <44215173+casnz1601@users.noreply.github.com> Date: Fri, 9 Sep 2022 12:42:55 -0400 Subject: [PATCH] =?UTF-8?q?Update=200797.=E6=89=80=E6=9C=89=E5=8F=AF?= =?UTF-8?q?=E8=83=BD=E7=9A=84=E8=B7=AF=E5=BE=84.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加Python实现 --- problems/0797.所有可能的路径.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0797.所有可能的路径.md b/problems/0797.所有可能的路径.md index a51590f2..f1f867f7 100644 --- a/problems/0797.所有可能的路径.md +++ b/problems/0797.所有可能的路径.md @@ -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