-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsolution.cpp
55 lines (52 loc) · 1.39 KB
/
solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* 30 / 30 test cases passed.
* Runtime: 12 ms
* Memory Usage: 10.4 MB
*/
class Solution {
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<vector<int>> ans;
vector<int> curr { 0 };
dfs(graph, 0, ans, curr);
return ans;
}
void dfs(vector<vector<int>>& graph, int idx, vector<vector<int>>& path, vector<int>& curr) {
if (idx + 1 == graph.size()) {
path.emplace_back(curr);
return;
}
for (auto& next: graph[idx]) {
curr.emplace_back(next);
dfs(graph, next, path, curr);
curr.pop_back();
}
}
};
/**
* 30 / 30 test cases passed.
* Runtime: 8 ms
* Memory Usage: 10.4 MB
*/
class Solution2 {
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
int n = graph.size();
vector<vector<int>> ans;
vector<int> curr { 0 };
curr.reserve(n);
dfs(graph, 0, n - 1, ans, curr);
return ans;
}
void dfs(vector<vector<int>>& graph, int idx, int last, vector<vector<int>>& path, vector<int>& curr) {
if (idx == last) {
path.emplace_back(curr);
return;
}
for (auto& next: graph[idx]) {
curr.emplace_back(next);
dfs(graph, next, last, path, curr);
curr.pop_back();
}
}
};