leetcode 797. 所有可能的路径 medium

 leetcode 797. 所有可能的路径  medium          

题目描述:

leetcode 797. 所有可能的路径 medium_第1张图片

解题思路:

dfs, 因为是无环图,所以不需要visited数组

代码:

//
class Solution {
public:
    vector> allPathsSourceTarget(vector>& graph) {
        vector> ret;
        vector path{0};
        dfs(ret, path, graph, 0);
        return ret;
        
    }

    void dfs(vector> &ret, vector &path, vector> &graph, int cur){
        if (cur == graph.size() - 1){
            ret.push_back(path);
            return;
        }

        for (int i: graph[cur]){
            path.push_back(i);
            dfs(ret, path, graph, i);
            path.pop_back();
        }
        
    }

};

你可能感兴趣的:(leetcode,图和并查集,leetcode)