Leetcode-797

All Paths From Source to Target

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <vector>

class Solution {
    void DFS(int n, int i, std::vector<int>& path, 
            std::vector<std::vector<int>>& graph, std::vector<std::vector<int>>& res) {
        path.push_back(i);
        if (i == n - 1) {
            res.push_back(path);
        }
        for (auto& j : graph[i]) {
            DFS(n, j, path, graph, res);
        }
        path.pop_back();
    }
    
public:
    std::vector<std::vector<int>> allPathsSourceTarget(std::vector<std::vector<int>>& graph) {
        int n = graph.size();
        std::vector<std::vector<int>> res;
        std::vector<int> path;
        path.reserve(n);
        DFS(n, 0, path, graph, res);
        return res;
    }
};

Leetcode-797

Licensed under CC BY-NC-SA 4.0