Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a7da6e2

Browse files
feat: add swift implementation to lcof2 problem: No.110 (doocs#3688)
1 parent 1768a6e commit a7da6e2

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

‎lcof2/剑指 Offer II 110. 所有路径/README.md‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,35 @@ func allPathsSourceTarget(graph [][]int) [][]int {
189189
}
190190
```
191191

192+
#### Swift
193+
194+
```swift
195+
class Solution {
196+
private var results = [[Int]]()
197+
private var graph = [[Int]]()
198+
199+
func allPathsSourceTarget(_ graph: [[Int]]) -> [[Int]] {
200+
self.graph = graph
201+
var path = [0]
202+
dfs(0, &path)
203+
return results
204+
}
205+
206+
private func dfs(_ node: Int, _ path: inout [Int]) {
207+
if node == graph.count - 1 {
208+
results.append(Array(path))
209+
return
210+
}
211+
212+
for next in graph[node] {
213+
path.append(next)
214+
dfs(next, &path)
215+
path.removeLast()
216+
}
217+
}
218+
}
219+
```
220+
192221
<!-- tabs:end -->
193222

194223
<!-- solution:end -->
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
private var results = [[Int]]()
3+
private var graph = [[Int]]()
4+
5+
func allPathsSourceTarget(_ graph: [[Int]]) -> [[Int]] {
6+
self.graph = graph
7+
var path = [0]
8+
dfs(0, &path)
9+
return results
10+
}
11+
12+
private func dfs(_ node: Int, _ path: inout [Int]) {
13+
if node == graph.count - 1 {
14+
results.append(Array(path))
15+
return
16+
}
17+
18+
for next in graph[node] {
19+
path.append(next)
20+
dfs(next, &path)
21+
path.removeLast()
22+
}
23+
}
24+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /