https://leetcode-cn.com/problems/all-paths-from-source-to-target/solution/797-cji-hu-shuang-bai-de-dfsjie-fa-by-ff-mff3/
- 所有可能的路径
给一个有 n 个结点的有向无环图,找到所有从 0 到 n-1 的路径并输出(不要求按顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号结点所能到达的下一些结点(译者注:有向图是有方向的,即规定了 a→b 你就不能从 b→a )空就是没有下一个结点了。
示例 1:
797. 所有可能的路径
输入:graph = [[1,2],[3],[3],[]]
输出:[[0,1,3],[0,2,3]]
解释:有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3
示例 2:
输入:graph = [[4,3,1],[3,2,4],[3],[4],[]]
输出:[[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
示例 3:
输入:graph = [[1],[]]
输出:[[0,1]]
示例 4:
输入:graph = [[1,2,3],[2],[3],[]]
输出:[[0,1,2,3],[0,2,3],[0,3]]
示例 5:
输入:graph = [[1,3],[2],[3],[]]
输出:[[0,1,2,3],[0,3]]
提示:
n == graph.length
2 <= n <= 15
0 <= graph[i][j] < n
graph[i][j] != i
保证输入为有向无环图 (GAD)
class Solution {
private:
// i表示当前的点
// n表示点的数量,也是结束标志
// res是结果
// curr是当前的路径
void dfs(int i, int n, vector<vector<int>>& res, vector<int>& curr, const vector<vector<int>>& graph)
{
if (i < n-1)
{
for (int next : graph[i])
{
curr.push_back(next);
dfs(next, n, res, curr, graph);
// 记得回溯
curr.pop_back();
}
}
else
{
// 递归结束了
res.push_back(curr);
}
}
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<vector<int>> res;
// 初始从0开始
vector<int> curr{0};
int n = graph.size();
dfs(0, n, res, curr, graph);
return res;
}
};