这个真没绕过来。。参考了答案,结果答案的效果也不怎么样
note: list连接,可以直接用“+”拼接起来
class Solution(object): def allPathsSourceTarget(self, graph): """ :type graph: List[List[int]] :rtype: List[List[int]] """ lenth = len(graph) def findpath(node): if node == lenth - 1: return [[lenth - 1]] ans = [] for i in graph[node]: for path in findpath(i): ans.append([node]+path) return ans return findpath(0)
483ms 6.4%
------------------------------------------------------------------
class Solution(object): def allPathsSourceTarget(self, graph, i = 0, q = [0]): """ :type graph: List[List[int]] :rtype: List[List[int]] """ if i==0: global ans ans = [] if i == len(graph) - 1: ans.append(q) for node in graph[i]: self.allPathsSourceTarget(graph, node, q+[node]) return ans
281ms 94.19%
note:可以修改输入,比中间加一个递归函数效果要好
这个方法最好,也最容易理解
但是总的思想是和我一开始是一致的,即node到lenth-1的距离就是[node]+[graph[node]到lenth-1的距离],然后递归调用
------------------------------------------------------------------
note: list.pop(index)删除list中下标为index的元素。不填则默认最后一个(即下标index=-1)元素
eg: a=[1,2,3,4]
则:print a.pop(1) #2
print a #[1,3,4]
print a.pop() #4
print a #[1,3]
class Solution(object): def allPathsSourceTarget(self, graph, i = 0, q = [0]): """ :type graph: List[List[int]] :rtype: List[List[int]] """ N = len(graph) - 1 paths = [[0]] ans = [] while paths: path = paths.pop() for n in graph[path[-1]]: if n == N: ans.append(path + [n]) else: paths.append(path + [n]) return ans
330ms 44.91%
难能可贵是没有用函数递归调用
脑细胞不够用