797. All Paths From Source to Target
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> result = new LinkedList<>();
recursion(graph, 0, new LinkedList<Integer>(), result);
return result;
}
private void recursion(int[][] graph, int i, List<Integer> list, List<List<Integer>> result){
list.add(i);
if(i==graph.length-1){
// make a copy of all elements in list,
// and add it to a new list
List<Integer> ans = new LinkedList(list);
result.add(ans);
}
// i will be always valid
int[] children = graph[i];
for(int child: children){
recursion(graph, child, list, result);
}
// backtrack
list.remove(list.size()-1);
}
}
Last updated
Was this helpful?