Description
斐波那契数,通常用 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fibonacci-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Solution 1 迭代
class Solution:
def fib(self, N: int) -> int:
pre, cur = 0, 1
if N == 0: return 0
elif N == 1: return 1
for i in range(N-1):
ans = pre + cur
pre = cur
cur = ans
return ans
Solution 2 递归
class Solution:
def fib(self, N: int) -> int:
if N == 0: return 0
if N == 1: return 1
return self.fib(N-1) + self.fib(N-2)
Solution 3 递归剪枝
class Solution:
def fib(self, N: int) -> int:
hashmap = {0: 1, 1: 1}
def helper(N):
if N == 0: return 0
if N == 1: return 1
if N in hashmap:
return hashmap[N]
hashmap[N] = helper(N-1) + helper(N-2)
return hashmap[N]
return helper(N)
# hashmap声明为私有变量才可在函数内更改
# return hashmap[N]
Solution 4 通项公式
class Solution:
def fib(self, N: int) -> int:
from math import sqrt
phi = (1 + sqrt(5))/2
fib = round(pow(phi, N)/sqrt(5))
return fib