797. All Paths From Source to Target

Problem:

Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any order.

The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists.

Example:

Input: [[1,2], [3], [3], []] 
Output: [[0,1,3],[0,2,3]] 
Explanation: The graph looks like this:
0--->1
|    |
v    v
2--->3
There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.

Note:

  • The number of nodes in the graph will be in the range [2, 15].
  • You can print different paths in any order, but you should keep the order of nodes inside one path.

思路

Solution (C++):

vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
    vector<vector<int>> all_path;
    vector<int> path;
    dfs(graph, all_path, path, 0);
    return all_path;
}
void dfs(vector<vector<int>>& g, vector<vector<int>>& res, vector<int>& path, int cur) {
    path.push_back(cur);
    if (cur == g.size()-1)  res.push_back(path);
    else
        for (auto node : g[cur])
            dfs(g, res, path, node);
    path.pop_back();
}

性能

Runtime: 72 ms  Memory Usage: 10.4 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

posted @ 2020-04-19 22:51  littledy  阅读(73)  评论(0编辑  收藏  举报