版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41427758/article/details/80292387
题目描述
- 写一个函数,输入n,求斐波那契(Fibonacci)数列的第n项。斐波那契数列的定义如下:
解题思路:
- 递归的解法
- 存在效率问题,很多的重复计算
- 循环的解法:时间复杂度
class Solution:
def __init__(self, N):
self.N = N
def Recursive(self, N):
if N == 0:
return 0
elif N == 1:
return 1
else: return self.Recursive(N - 1) + self.Recursive(N - 2)
def loop_method(self, N):
if N == 0:
return 0
elif N == 1:
return 1
firstNum = 0
secondNum = 1
result = 0
for i in range(2, N + 1):
result = firstNum + secondNum
firstNum = secondNum
secondNum = result
return result