797. All Paths From Source to Target

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.

无循环图的路径搜索问题。

 1 class Solution {
 2 public:
 3     void helper(vector<vector<int>>& graph, vector<vector<int>> &res, 
 4                 vector<int> &temp, int &Target) {
 5         if (temp.back() == Target) {
 6             res.push_back(temp);
 7             return;
 8         }
 9         vector<int> rt = graph[temp.back()];
10         for (int i=0; i<rt.size(); ++i) {
11             temp.push_back(rt[i]);
12             helper(graph, res, temp, Target);
13             temp.pop_back();
14         }
15         
16         
17     }
18     vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
19         int Target = graph.size() - 1;
20         vector<vector<int>> res;
21         vector<int> temp;
22         if (Target < 0)
23             return res;
24         temp.push_back(0);
25         helper(graph, res, temp, Target);
26         return res;
27     }
28 };

 

posted @ 2018-03-12 20:19  Zzz...y  阅读(274)  评论(0编辑  收藏  举报