★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-syvvbdfq-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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,git
F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), for N > 1.
Given N
, calculate F(N)
. github
Example 1:微信
Input: 2 Output: 1 Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Example 2:oop
Input: 3 Output: 2 Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
Example 3:spa
Input: 4 Output: 3 Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
Note:code
0 ≤ N
≤ 30.orm
斐波那契數,一般用 F(n)
表示,造成的序列稱爲斐波那契數列。該數列由 0
和 1
開始,後面的每一項數字都是前面兩項數字的和。也就是:htm
F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
給定 N
,計算 F(N)
。 blog
示例 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.
提示:
N
≤ 301 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 }