1.直接使用了递归算法
def Fibonacci1(self, n):
# write code here
# F(0) = 0, F(1) = 1
# F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
if (n==0):
return 0
elif (n==1):
return 1
elif (n>1):
return self.Fibonacci1(n-1)+self.Fibonacci1(n-2)
return None
通过直接使用递归发现算法很耗时,这个时候想到了使用辅助数组的办法,将已经计算过的数字保存起来。
2.使用辅助数组优化
def Fibonacci(self, n):
# write code here
# F(0) = 0, F(1) = 1
# F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
indexs = [] # 保存下标的数组
values = [] # 保存下标对应的值的数组
if (n==0):
return 0
elif (n==1):
return 1
elif (n>1):
if (n-1) not in indexs:
indexs.append(n-1)
values.append(self.Fibonacci(n-1))
if (n-2) not in indexs:
indexs.append(n-2)
values.append(self.Fibonacci(n-2))
if (n-1) in indexs and (n-2) in indexs:
return values[indexs.index(n-1)]+values[indexs.index(n-2)]
return None
没有想到使用了辅助数组的办法,比没有使用更加耗时,应该是查询下标的过程很耗时
3.使用循环
def xunhuan(self,n):
a = 1 # 较大
b = 0 # 较小
for i in range(0,n-2):
sum = a + b
b = a
a = sum
return sum
上一级大的数与上一级的两个数之和相加