LeetCode 797. All Paths From Source to Target
作者:互联网
LeetCode 797. All Paths From Source to Target (所有可能的路径)
题目
链接
https://leetcode-cn.com/problems/all-paths-from-source-to-target/
问题描述
给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)
graph[i] 是一个从节点 i 可以访问的所有节点的列表(即从节点 i 到节点 graph[i][j]存在一条有向边)。
示例
输入:graph = [[1,2],[3],[3],[]]
输出:[[0,1,3],[0,2,3]]
解释:有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3
提示
输入:graph = [[1,2],[3],[3],[]]
输出:[[0,1,3],[0,2,3]]
解释:有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3
思路
考虑到有向无环图,就无需判断visit了,直接用图的遍历算法。
复杂度分析
时间复杂度 O(n*2^n)
空间复杂度 O(n)
代码
Java
List<List<Integer>> res = new LinkedList<>();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
LinkedList<Integer> path = new LinkedList<>();
traverse(graph, 0, path);
return res;
}
void traverse(int[][] graph, int s, LinkedList<Integer> path) {
path.add(s);
int n = graph.length;
if (n - 1 == s) {
res.add(new LinkedList<>(path));
path.removeLast();
return;
}
for (int v : graph[s]) {
traverse(graph, v, path);
}
path.removeLast();
}
标签:797,Paths,Target,int,graph,复杂度,path,节点,LinkedList 来源: https://www.cnblogs.com/blogxjc/p/16124990.html