算法题(程序员面试宝典)
解题思路主要来源于leetcode官方与《程序员面试宝典》&labuladong
797. 所有可能的路径
给一个有 n 个结点的有向无环图,找到所有从 0 到 n-1 的路径并输出(不要求按顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号结点所能到达的下一些结点(译者注:有向图是有方向的,即规定了 a→b 你就不能从 b→a )空就是没有下一个结点了。
示例 1:
输入:graph = [[1,2],[3],[3],[]]
输出:[[0,1,3],[0,2,3]]
解释:有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3
示例 2:
输入:graph = [[4,3,1],[3,2,4],[3],[4],[]]
输出:[[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
示例 3:
输入:graph = [[1],[]]
输出:[[0,1]]
示例 4:
输入:graph = [[1,2,3],[2],[3],[]]
输出:[[0,1,2,3],[0,2,3],[0,3]]
示例 5:
输入:graph = [[1,3],[2],[3],[]]
输出:[[0,1,2,3],[0,3]]
提示:
结点的数量会在范围 [2, 15] 内。
你可以把路径以任意顺序输出,但在路径内的结点的顺序必须保证。
解题方法
解题思路1
class Solution {
List<List<Integer>> res = new LinkedList<>();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
LinkedList<Integer> path = new LinkedList<>();
traverse(graph,0,path);
return res;
}
public void traverse(int[][] graph,int node,LinkedList<Integer> path){
//图遍历, 与回溯算法不同在于做出选择和撤销选择的位置不同,因为关注点不同,回溯关注于路径,而该图遍历关注于节点
//做出选择
path.add(node);
//结束条件
int n = graph.length;
if(node==n-1){
//找到n-1的节点,将当前路径添加至结果集中
res.add(new LinkedList(path));
//在此要做出撤销选择,此处与回溯不同
path.removeLast();
return;
}
//遍历当前节点node相邻的节点
for(int neighbour:graph[node]){
traverse(graph,neighbour,path);
}
//撤销选择,将当前节点移除路径
path.removeLast();
}
}