797. 所有可能的路径

165 阅读1分钟

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

797. 所有可能的路径

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

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

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

  • 示例 1:

image.png

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

  • 示例 2:

image.png

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

解题思路

使用深度优先搜索,以0节点为起点,查找终点n-1。使用list记录路径上的点。每次我们遍历到点 n−1,就将list中记录的路径加入到答案中

代码

class Solution {
    List<List<Integer>> res=new ArrayList<>();
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {

        SallPathsSourceTarget(graph,0,new ArrayList<Integer>(){{add(0);}});
        return res;
    }
    public void SallPathsSourceTarget(int[][] graph,int cur,List<Integer> list) {

        if (graph.length-1==cur)
        {
            res.add(new ArrayList<>(list));
            return;
        }
        for (int next : graph[cur]) {
            list.add(next);
            SallPathsSourceTarget(graph, next, list);
            list.remove(list.size()-1);
        }

    }
}

时间复杂度:O(n x 2^n),其中 nn 为图中点的数量。我们可以找到一种最坏情况,即每一个点都可以去往编号比它大的点。此时路径数为 O(2^n),且每条路径长度为 O(n),因此总时间复杂度为 O(n x 2^n)

空间复杂度:O(n),其中 n 为点的数量。主要为栈空间的开销。注意返回值不计入空间复杂度。