Created
June 17, 2020 19:10
-
-
Save liyunrui/2475ea90f9e6df7ce4fb40c4170a5f3f to your computer and use it in GitHub Desktop.
leetcode-DAG
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: | |
""" | |
Thought process: | |
1. we use backtracking to generate all possible pathes from node 0 to node n-1 | |
Time complexity analysis: | |
Except the starting and ending node, each node could be included in the path or not. In an exntrem case, there're goingt to 2^(n-1) pathes from node 0 to node n-1 .So, time complexity could roughly be 2 raise to power of n. | |
T:(2^n) | |
""" | |
n = len(graph) | |
self.ans = [] | |
def backtrack(cur, path): | |
if cur == n - 1: | |
# meet the target node | |
self.ans.append(path) | |
for nei in graph[cur]: | |
backtrack(nei, path + [nei]) | |
source_n, path = 0, [0] | |
backtrack(source_n, path) | |
return self.ans |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment