797. 所有可能的路径
思路:DFS搜索即可
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
/**
* 797. 所有可能的路径
*/
public class Solution797 {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> res = new ArrayList<>();
Deque<Integer> stack = new ArrayDeque<>();
stack.add(0);
int end = graph.length - 1;
dfs(graph, 0, end, res, stack);
return res;
}
public void dfs(int[][] graph, int node, int end, List<List<Integer>> res, Deque<Integer> stack) {
if (node == end) {
res.add(new ArrayList<>(stack));
return;
}
for (int nextNode : graph[node]) {
stack.add(nextNode);
dfs(graph, nextNode, end, res, stack);
stack.remove(nextNode);
}
}
public static void main(String args[]) {
Solution797 solution797 = new Solution797();
solution797.allPathsSourceTarget(new int[][]{{1,2},{3},{3},{}});
}
}