https://leetcode-cn.com/problems/all-paths-from-source-to-target/
思路:
d
f
s
dfs
dfs回溯即可,感觉没什么好说的。因为是有向无环图,所以在一次
d
f
s
dfs
dfs过程中不可能访问到已经访问过的节点,不需要引入额外的标记数组。
class Solution {
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
int n=graph.size();
vector<vector<int>> ans;
vector<int> path;
function<void(int)> dfs=[&](int cur)->void
{
path.push_back(cur);
if(cur==n-1)
{
ans.push_back(path);
path.pop_back();
return ;
}
for(int nxt:graph[cur])
{
dfs(nxt);
}
path.pop_back();
};
dfs(0);
return ans;
}
};