LeetCode 每日一题 797. 所有可能的路径

953 阅读1分钟

这是我参与8月更文挑战的第25天,活动详情查看:8月更文挑战

797. 所有可能的路径

给你一个有 n 个节点的 有向无环图(DAG) ,请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序

二维数组的第 i 个数组中的单元都表示有向图中 i 号节点所能到达的下一些节点,空就是没有下一个结点了。

译者注:有向图是有方向的,即规定了 a→b 你就不能从 b→a 。

示例 1:

img

输入:graph = [[1,2],[3],[3],[]]
输出:[[0,1,3],[0,2,3]]
解释:有两条路径 0 -> 1 -> 30 -> 2 -> 3

img

输入: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]]

提示:

  • n == graph.length
  • 2 <= n <= 15
  • 0 <= graph[i][j] < n
  • graph[i][j] != i(即,不存在自环)
  • graph[i] 中的所有元素 互不相同
  • 保证输入为 有向无环图(DAG)

方法一

深度优先遍历 + 回溯:

由于n的范围只有2~15,直接暴力即可;

深度优先遍历,每次传入当前遍历到的结点u,和邻接矩阵graph

u等于n-1时,符合题目所给的要求;将此次路径加入到答案中;

特别地,因为本题中的图为有向无环图(DAG),搜索过程中不会反复遍历同一个点,因此我们无需判断当前点是否遍历过。

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        LinkedList path = new LinkedList();
        path.add(0);
        dfs(0, graph, path);
        return res;
    }
    void dfs(int u, int[][] graph, LinkedList<Integer> path) {
        if (path.getLast() == graph.length - 1) {
            res.add(new LinkedList(path));
            return;
        }
        for (int i = 0; i < graph[u].length; i ++ ) {
            path.add(graph[u][i]);
            dfs(graph[u][i], graph, path);
            path.removeLast();
        }
        return;
    }
}

时间复杂度: O(n * 2^n)

空间复杂度: O(n)