【发布时间】:2022-01-17 13:26:49
【问题描述】:
所以问题是找到从源到目标的所有路径 (https://leetcode.com/problems/all-paths-from-source-to-target/)。
# code snippet 1
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
paths = []
def dfsPath(node):
if node == len(graph) - 1:
print(validPath) # line 6
paths.append(validPath) # line 7
return paths
else:
for n in graph[node]:
validPath.append(n)
dfsPath(n)
validPath.pop()
validPath = [0]
dfsPath(0)
return paths
# code snippet 2
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
paths = []
def dfsPath(node):
if node == len(graph) - 1:
print(validPath) # line 6
paths.append(validPath.copy()) # line 7
return paths
else:
for n in graph[node]:
validPath.append(n)
dfsPath(n)
validPath.pop()
validPath = [0]
dfsPath(0)
return paths
上面两个代码 sn-ps 的唯一变化是第 7 行。我在第 6 行添加了 print 语句来显示 validPath 持有的内容。我的问题是为什么只添加 validPath 会导致与添加 validPath.copy() 时不同的输出(在第 7 行)。
【问题讨论】:
-
从两个屏幕截图看起来两个输出是相同的......
-
抱歉我的错误@Tanque,已修复