File tree 2 files changed +53
-0
lines changed
lcof2/剑指 Offer II 110. 所有路径
2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -189,6 +189,35 @@ func allPathsSourceTarget(graph [][]int) [][]int {
189
189
}
190
190
```
191
191
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
+
192
221
<!-- tabs:end -->
193
222
194
223
<!-- solution:end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments