剑指offer07-斐波那契数列

题目描述

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)。 n<=39 

示例

输入 4

返回值 3

知识点回顾

数组:这里用递归会报错“您的程序未能在规定时间内运行结束,请检查是否循环有错或算法复杂度过大”

改用数组可以巧妙解决

代码

#报超时:程序未能在规定时间内运行结束
#
-*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): # write code here
if n==0:
return 0
if n==1:
return 1
return Fibonacci(n-1)+Fibonacci(n-2) //

#在Pythontutor测试可执行

  a=Solution()
  a.Fibonacci(n=4)

 

 

#用数组实现
#
-*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): # write code here res=[0,1] while n>=len(res): res.append(res[-1]+res[-2]) return res[n]

 

posted @ 2020-11-16 20:02  foolangirl  阅读(69)  评论(0编辑  收藏  举报