File tree 2 files changed +55
-0
lines changed
2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change @@ -195,6 +195,36 @@ var fraction = function (cont) {
195
195
};
196
196
```
197
197
198
+ #### Swift
199
+
200
+ ``` swift
201
+ class Solution {
202
+ private var cont: [Int ] = []
203
+
204
+ func fraction (_ cont : [Int ]) -> [Int ] {
205
+ self .cont = cont
206
+ return dfs (0 )
207
+ }
208
+
209
+ private func dfs (_ i : Int ) -> [Int ] {
210
+ if i == cont.count - 1 {
211
+ return [cont[i], 1 ]
212
+ }
213
+ let next = dfs (i + 1 )
214
+ let a = next[0 ]
215
+ let b = next[1 ]
216
+ let x = a * cont[i] + b
217
+ let y = a
218
+ let g = gcd (x, y)
219
+ return [x / g, y / g]
220
+ }
221
+
222
+ private func gcd (_ a : Int , _ b : Int ) -> Int {
223
+ return b == 0 ? a : gcd (b, a % b)
224
+ }
225
+ }
226
+ ```
227
+
198
228
<!-- tabs: end -->
199
229
200
230
<!-- solution: end -->
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ private var cont : [ Int ] = [ ]
3
+
4
+ func fraction( _ cont: [ Int ] ) -> [ Int ] {
5
+ self . cont = cont
6
+ return dfs ( 0 )
7
+ }
8
+
9
+ private func dfs( _ i: Int ) -> [ Int ] {
10
+ if i == cont. count - 1 {
11
+ return [ cont [ i] , 1 ]
12
+ }
13
+ let next = dfs ( i + 1 )
14
+ let a = next [ 0 ]
15
+ let b = next [ 1 ]
16
+ let x = a * cont[ i] + b
17
+ let y = a
18
+ let g = gcd ( x, y)
19
+ return [ x / g, y / g]
20
+ }
21
+
22
+ private func gcd( _ a: Int , _ b: Int ) -> Int {
23
+ return b == 0 ? a : gcd ( b, a % b)
24
+ }
25
+ }
You can’t perform that action at this time.
0 commit comments