1. 程式人生 > 其它 >LeetCode 797. All Paths From Source to Target

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();
    }