LeetCode Solutions

797. All Paths From Source to Target

Time: $O(n \cdot 2^n)$

Space: $O(n \cdot 2^n)$

			

class Solution {
 public:
  vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
    vector<vector<int>> ans;
    dfs(graph, 0, {0}, ans);
    return ans;
  }

 private:
  void dfs(const vector<vector<int>>& graph, int u, vector<int>&& path,
           vector<vector<int>>& ans) {
    if (u == graph.size() - 1) {
      ans.push_back(path);
      return;
    }

    for (const int v : graph[u]) {
      path.push_back(v);
      dfs(graph, v, move(path), ans);
      path.pop_back();
    }
  }
};
			

class Solution {
  public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
    List<List<Integer>> ans = new ArrayList<>();
    dfs(graph, 0, new ArrayList<>(Arrays.asList(0)), ans);
    return ans;
  }

  private void dfs(int[][] graph, int u, List<Integer> path, List<List<Integer>> ans) {
    if (u == graph.length - 1) {
      ans.add(new ArrayList<>(path));
      return;
    }

    for (final int v : graph[u]) {
      path.add(v);
      dfs(graph, v, path, ans);
      path.remove(path.size() - 1);
    }
  }
}
			

class Solution:
  def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
    ans = []

    def dfs(u: int, path: List[int]) -> None:
      if u == len(graph) - 1:
        ans.append(path)
        return

      for v in graph[u]:
        dfs(v, path + [v])

    dfs(0, [0])
    return ans