剑指 Offer II 110. 所有路径(797. 所有可能的路径)
题目:
思路:
【1】回溯的方式
代码展示:
回溯的方式:
//时间1 ms击败100% //内存43.5 MB击败43.56% class Solution { public List<List<Integer>> allPathsSourceTarget(int[][] graph) { List<List<Integer>> res = new ArrayList<>(); List<Integer> path = new ArrayList<>(); path.add(0); dfsFindPath(graph,0,path,res); return res; } public void dfsFindPath(int[][] graph, int index, List<Integer> path, List<List<Integer>> res){ if (index == graph.length) return; for (int x : graph[index]){ path.add(x); if (x == graph.length - 1) { res.add(new ArrayList<>(path)); }else { dfsFindPath(graph,x,path,res); } path.remove(path.size()-1); } } }