回溯算法其實就是深搜,只不過這里的深搜是側重于在圖上搜索,回溯大多是在樹上搜索。
797.所有可能的路徑
完成
代碼
模板題
class Solution {List<List<Integer>> res = new ArrayList<>();List<Integer> path = new ArrayList<>();// 搜索以node為根的圖public void dfs(int[][] graph, int node) { if(node == graph.length-1){res.add(new ArrayList<>(path));return;}// 遍歷和node直連的所有節點for(int index = 0; index < graph[node].length; index++){path.add(graph[node][index]);dfs(graph, graph[node][index]);path.removeLast();}}public List<List<Integer>> allPathsSourceTarget(int[][] graph) {path.add(0);dfs(graph, 0);return res;}
}