在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ The Fibonacci numbers, commonly denoted F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), for N > 1. Given Example 1: Input: 2 Output: 1 Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. Example 2: Input: 3 Output: 2 Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. Example 3: Input: 4 Output: 3 Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. Note: 0 ≤ 斐波那契数,通常用 F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), 其中 N > 1. 给定 示例 1: 输入:2 输出:1 解释:F(2) = F(1) + F(0) = 1 + 0 = 1. 示例 2: 输入:3 输出:2 解释:F(3) = F(2) + F(1) = 1 + 1 = 2. 示例 3: 输入:4 输出:3 解释:F(4) = F(3) + F(2) = 2 + 1 = 3. 提示:
Runtime: 8 ms
Memory Usage: 18.3 MB
1 class Solution { 2 // f(0) = 0 3 // f(1) = 1 4 func fib(_ N: Int) -> Int { 5 guard N > 1 else { return N } 6 return processor(N, last: 1, llast: 0, anchor: 2) 7 } 8 9 func processor(_ n: Int, last: Int, llast: Int, anchor: Int) -> Int { 10 guard anchor < n else { return last + llast } 11 let value = last + llast 12 return processor(n, last: value, llast: last, anchor: anchor+1) 13 } 14 } 8ms 1 class Solution { 2 var cache : [Int:Int] = [:] 3 4 func fib(_ N: Int) -> Int { 5 if let fibAnswer = cache[N] { 6 return fibAnswer 7 } 8 9 if N < 2{ 10 return N 11 } 12 13 let answer = fib(N - 1) + fib(N - 2) 14 cache[N] = answer 15 return answer 16 } 17 } 12ms 1 class Solution { 2 func fib(_ N: Int) -> Int { 3 if N <= 1 { return N } 4 5 var f = [Int](repeating: 0, count: N + 1) 6 f[0] = 0 7 f[1] = 1 8 9 for i in 2...N { 10 f[i] = f[i - 2] + f[i - 1] 11 } 12 13 return f[N] 14 } 15 } 16ms 1 class Solution { 2 func fib(_ N: Int) -> Int { 3 if N < 2 { 4 return N 5 } 6 7 var preValue = 1 8 var prePreValue = 0 9 var loop = 1 10 var result = 0 11 12 while loop < N { 13 result = preValue + prePreValue 14 prePreValue = preValue 15 preValue = result 16 loop += 1 17 } 18 19 return result 20 } 21 } 24ms 1 class Solution { 2 func fib(_ N: Int) -> Int { 3 let ss = sqrt(5) 4 let n = N 5 return Int((asdfasd((ss + 1) / 2, n) - asdfasd((1 - ss) / 2, n)) / ss) 6 } 7 8 func asdfasd(_ x: Double, _ N: Int) -> Double { 9 var result: Double = 1 10 for _ in 0..<N { 11 result = result * x 12 } 13 return result 14 } 15 } 32ms 1 class Solution { 2 func fib(_ N: Int) -> Int { 3 if N == 0 || N == 1 { 4 return N 5 } 6 7 return fib(N-1) + fib(N-2) 8 } 9 }
|
请发表评论