LeetCode 797 All Paths From Source to Target
概述
https://leetcode.com/problems/all-paths-from-source-to-target/
递归法
和回溯法很像。
class Solution {
public:
vector<vector<int>> paths;
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<int> path;
helper(graph, 0, path);
return paths;
}
void helper(vector<vector<int>>& graph, int s, vector<int> path) {
path.push_back(s);
if (s == graph.size() - 1) {
paths.push_back(path);
// return;
}
for (auto n : graph[s]) {
helper(graph, n, path);
}
path.pop_back();
}
};
真的吗?其实这里根本没有必要弹出,因为你这里的 path 是局部变量,函数结束后就销毁了。
当然,当 path 共享时,就必须弹出了。
class Solution {
public:
vector<vector<int>> paths;
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<int> path;
helper(graph, 0, path);
return paths;
}
void helper(vector<vector<int>>& graph, int s, vector<int>& path) {
path.push_back(s); // 这里自动 copy 了向量
if (s == graph.size() - 1) {
paths.push_back(path);
}
for (auto n : graph[s]) {
helper(graph, n, path);
}
path.pop_back();
}
};