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 27 28 29 30 31 32 33 34 35 36
| class Solution { public: vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) { vector<vector<int>> ret; vector<int> cannotReach(graph.size(), 0); vector<int> tmp; dfs(graph, ret, tmp, cannotReach, 0, graph.size() - 1); return ret; } private: bool dfs(vector<vector<int>>& graph, vector<vector<int>>& ret, vector<int>& tmp, vector<int>& cannotReach, int node, int target) { if(cannotReach[node]) return false; tmp.push_back(node); if(node == target) { ret.push_back(tmp); tmp.pop_back(); return true; } if(graph[node].empty()) { tmp.pop_back(); return false; } bool res = false; for(auto& next : graph[node]) if(!dfs(graph, ret, tmp, cannotReach, next, target)) cannotReach[node] = 1; else res = true; tmp.pop_back(); return res; } };
|