LeetCode 797. 所有可能的路径
原题链接
简单
作者:
我是java同学
,
2023-08-08 09:46:34
,
所有人可见
,
阅读 73
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
void dfs(int u, vector<vector<int>>& graph) {
if (u == graph.size() - 1) {
res.push_back(path);
return;
}
for (auto& v: graph[u]) {
path.push_back(v);
dfs(v, graph);
path.pop_back();
}
}
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
path.push_back(0);
dfs(0, graph);
return res;
}
};
class Solution {
public:
int n;
vector<vector<int>> res;
vector<int> path;
vector<vector<int>> g;
void dfs(int u) {
if (u == n - 1) {
res.push_back(path);
return;
}
for (auto& v: g[u]) {//从当前点走到相连的下一个点
path.push_back(v);
dfs(v);
path.pop_back();
}
}
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
g = graph;
n = g.size();
path.push_back(0);
dfs(0);
return res;
}
};