1. 程式人生 > 其它 >【LeetCode-797】所有可能的路徑

【LeetCode-797】所有可能的路徑

問題

給一個有n個結點的有向無環圖,找到所有從0到n-1的路徑並輸出(不要求按順序)

二維陣列的第 i 個數組中的單元都表示有向圖中 i 號結點所能到達的下一些結點(譯者注:有向圖是有方向的,即規定了 a→b 你就不能從 b→a )空就是沒有下一個結點了。

示例

輸入: graph = [[1,2],[3],[3],[]]
輸出: [[0,1,3],[0,2,3]]
解釋: 有兩條路徑 0 -> 1 -> 3 和 0 -> 2 -> 3

解答

class Solution {
public:
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        ans.push_back(0);
        dfs(graph, 0);
        return res;
    }
private:
    vector<vector<int>> res;
    vector<int> ans;
    void dfs(vector<vector<int>>& graph, int pos) {
        if (pos == graph.size() - 1) res.push_back(ans);
        for (int i : graph[pos]) {
            ans.push_back(i);
            dfs(graph, i);
            ans.pop_back();
        }
    }
};