797. All Paths From Source to Target
仅供自己学习
思路:
这个题目给的graph是一个二维数组,例如,[[1,2],[3],[3],[]],[1,2]是下标为0的位置的数组,所以是0结点的出度边的终点,就是0指向1,2.同样对于下标为1的位置是[3],则1节点指向3.
那么我们就可以用DFS,从0结点开始从1深入,出来之后再从2深入即可,因为题目求的是0到n-1的路径,所以将一条路径加入到res二维数组的条件是当前结点cur=size()-1。
代码:
1 class Solution { 2 public: 3 void DFS(vector<vector<int>>& graph,vector<vector<int>>&res,vector<int> path,int cur){ 4 path.push_back(cur); 5 if(cur==graph.size()-1) res.push_back(path); 6 else for(auto neighbor:graph[cur]) DFS(graph,res,path,neighbor); 7 } 8 vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) { 9 vector<vector<int>> res; 10 DFS(graph,res,{},0); 11 return res; 12 } 13 14 };
优化
1 class Solution { 2 public: 3 vector<vector<int>> res; 4 vector<int> path; 5 void DFS(vector<vector<int>>& graph,int cur){ 6 path.push_back(cur); 7 if(cur==graph.size()-1){ 8 res.push_back(path); 9 return; 10 } 11 for(int i=0;i<graph[cur].size();++i){ 12 DFS(graph,graph[cur][i]); 13 path.pop_back(); 14 } 15 } 16 vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) { 17 DFS(graph,0); 18 return res; 19 } 20 21 };