[Swift]LeetCode509. 斐波那契数 | Fibonacci Number
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10392466.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
The Fibonacci numbers, commonly denoted F(n)
form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0
and 1
. That is,
F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), for N > 1.
Given N
, calculate F(N)
.
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 ≤ N
≤ 30.
斐波那契数,通常用 F(n)
表示,形成的序列称为斐波那契数列。该数列由 0
和 1
开始,后面的每一项数字都是前面两项数字的和。也就是:
F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
给定 N
,计算 F(N)
。
示例 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.
提示:
- 0 ≤
N
≤ 30
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 }