题目链接:https://leetcode-cn.com/problems/all-paths-from-source-to-target/
题意:
给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号节点所能到达的下一些节点,空就是没有下一个结点了。
译者注:有向图是有方向的,即规定了 a→b 你就不能从 b→a 。
方法:深搜递归
class Solution {
private:
vector<vector<int>> _graph;
vector<vector<int>> ans;//存储所有满足要求的向量
int size;//存储有几个节点
void dfs(int index,vector<int> vct)//深搜寻找可行的节点
{
if(index==size-1)//假如是最后一个节点
{
ans.push_back(vct);//将该向量插入答案向量
return ;
}
for(auto i:_graph[index])//枚举
{
vct.emplace_back(i);//在向量中插入该元素
dfs(i,vct);//深搜
vct.erase(vct.end()-1);//删除最有一个元素
}
}
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
_graph = graph;
size = graph.size();//记录有几个节点
vector<int> vct;//用来存储一条路径
vct.emplace_back(0);
dfs(0,vct);//进行深搜
return ans;//返回答案
}
};
优化:直接引用,不用新开存储空间
class Solution {
private:
void dfs(int index,vector<vector<int>>& graph,int size,vector<int> &vct,vector<vector<int>>& ans)//深搜寻找可行的节点
{
if(index==size-1)//假如是最后一个节点
{
ans.push_back(vct);//将该向量插入答案向量
return ;
}
for(auto i:graph[index])//枚举
{
vct.emplace_back(i);//在向量中插入该元素
dfs(i,graph,size,vct,ans);//深搜
vct.pop_back();//删除最有一个元素
}
}
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<vector<int>> ans;//存储所有满足要求的向量
int size = graph.size();//记录有几个节点
vector<int> vct;//用来存储一条路径
vct.emplace_back(0);
dfs(0,graph,size,vct,ans);//进行深搜
return ans;//返回答案
}
};