Backtracking DFS
Time O(2ⁿ × n) worst case Space O(n) besides the outputpath.add(u); if u is the target, record a copy; else recurse on each successor; path.remove(last).
import java.util.*;
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> out = new ArrayList<>();
dfs(graph, 0, new ArrayList<>(), out);
return out;
}
private void dfs(int[][] g, int u, List<Integer> path, List<List<Integer>> out) {
path.add(u);
if (u == g.length - 1) out.add(new ArrayList<>(path));
else for (int v : g[u]) dfs(g, v, path, out);
path.remove(path.size() - 1);
}
}Verdict: Output-sensitive; can't do better in general.