797. All Paths From Source to Target

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> resultList = new ArrayList<>();
List<Integer> path = new ArrayList<>(graph.length);
dfs(resultList, path, graph, 0);
return resultList;
}

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

for (int next : graph[i]) {
path.add(i);
dfs(resultList, path, graph, next);
path.remove(path.size() - 1);
}
}
}

References

797. All Paths From Source to Target
剑指 Offer II 110. 所有路径