leetcode 797 所有可能的路径

描述

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

二维数组的第 i 个数组中的单元都表示有向图中 i 号结点所能到达的下一些结点(译者注:有向图是有方向的,即规定了a→b你就不能从b→a)空就是没有下一个结点了。

示例:
输入: [[1,2], [3], [3], []]
输出: [[0,1,3],[0,2,3]]
解释: 图是这样的:
0—>1
| |
v v
2—>3
这有两条路: 0 -> 1 -> 3 和 0 -> 2 -> 3.
提示:

结点的数量会在范围 [2, 15] 内。
你可以把路径以任意顺序输出,但在路径内的结点的顺序必须保证。

思路

dfs典型题目,两种写法

写法一

class Solution {
public:
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        vector<vector<int>> res;
        vector<int> path;
        dfs(res,path,0,graph);
        return res;
    }
    
    void dfs(vector<vector<int>> &res,vector<int> &path,int p,vector<vector<int>>& graph){
        int n=graph.size();
        path.push_back(p);
        if(p==n-1) res.push_back(path);
        else for(int next:graph[p])dfs(res,path,next,graph);
        path.pop_back();
    }
};

写法二

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

参考:
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/118691/C%2B%2BPython-Backtracking
https://leetcode.com/problems/all-paths-from-source-to-target/discuss/118713/Java-DFS-Solution

猜你喜欢

转载自blog.csdn.net/yrk0556/article/details/89407604