思路
- 一般这种所有路径问题,适合用DFS
- 因为这个是有向图且不存在环 所以不需要visited集合!
PS: 我倒认为这个更像回溯~
class Solution {
List<List<Integer>> result;
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
result = new ArrayList<>();
dfs(graph,0,new ArrayList<>());
return result;
}
private void dfs(int[][] graph , int i , List<Integer> path){
path.add(i);
if(i == graph.length - 1)
result.add(new ArrayList<>(path));
else{
for(int neighbour : graph[i]){
dfs(graph,neighbour,path);
}
}
path.remove(path.size()-1);
}
}