diff --git "a/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/README.md" "b/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/README.md" index f2c5e01372cdd..c819541cadd16 100644 --- "a/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/README.md" +++ "b/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/README.md" @@ -195,6 +195,36 @@ var fraction = function (cont) { }; ``` +#### Swift + +```swift +class Solution { + private var cont: [Int] = [] + + func fraction(_ cont: [Int]) -> [Int] { + self.cont = cont + return dfs(0) + } + + private func dfs(_ i: Int) -> [Int] { + if i == cont.count - 1 { + return [cont[i], 1] + } + let next = dfs(i + 1) + let a = next[0] + let b = next[1] + let x = a * cont[i] + b + let y = a + let g = gcd(x, y) + return [x / g, y / g] + } + + private func gcd(_ a: Int, _ b: Int) -> Int { + return b == 0 ? a : gcd(b, a % b) + } +} +``` + diff --git "a/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.swift" "b/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.swift" new file mode 100644 index 0000000000000..90097779be77a --- /dev/null +++ "b/lcp/LCP 02. \345\210\206\345\274\217\345\214\226\347\256\200/Solution.swift" @@ -0,0 +1,25 @@ +class Solution { + private var cont: [Int] = [] + + func fraction(_ cont: [Int]) -> [Int] { + self.cont = cont + return dfs(0) + } + + private func dfs(_ i: Int) -> [Int] { + if i == cont.count - 1 { + return [cont[i], 1] + } + let next = dfs(i + 1) + let a = next[0] + let b = next[1] + let x = a * cont[i] + b + let y = a + let g = gcd(x, y) + return [x / g, y / g] + } + + private func gcd(_ a: Int, _ b: Int) -> Int { + return b == 0 ? a : gcd(b, a % b) + } +}