797. All Paths From Source to Target 發表於 2023-02-13 | 分類於 leetcode problemsolution1234567891011121314151617181920212223242526272829class Solution {public: void traverse(vector<vector<int>>& graph, int cur, vector<int>& path, vector<vector<int>>& ret){ // 添加節點至路徑 path.push_back(cur); if(path.back() == graph.size()-1){ // 抵達終點 ret.push_back(path); path.pop_back(); return; } // 遞迴每個相鄰節點 for(int neighbor:graph[cur]){ traverse(graph, neighbor, path, ret); } path.pop_back(); } vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) { vector<vector<int>> ret; vector<int> path; traverse(graph, 0, path, ret); return ret; }}; 12345678910111213141516171819202122class Solution {public: vector<vector<int>> ret; void dfs(vector<vector<int>> &graph, vector<int> &path, int start){ path.push_back(start); if(!path.empty() && path.back() == graph.size()-1){ ret.push_back(path); } for(auto a:graph[start]){ dfs(graph, path, a); } path.pop_back(); } vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) { vector<int> path; dfs(graph, path, 0); return ret; }}; analysis time complexity O(V+E) space complexity O(V)