剑指offer_面试题10 : 斐波那契数列( python实现 )

斐波那契数列 ( python实现 )

一、题目描述

题目一:求斐波那契数列的第 n 项
写一个函数,输入 n ,求Fibonacci数列的第n项。斐波那契数列定义如下:

f ( n ) = { 0 n = 0 1 n = 1 f ( n − 1 ) + f ( n − 2 ) n > 1 f(n)= \left\{ \begin{aligned} &0 & n=0\\ &1 & n=1 \\ &f(n-1)+f(n-2) & n>1 \end{aligned} \right. f(n)=01f(n1)+f(n2)n=0n=1n>1

题目二:青蛙跳台阶问题
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上1个n级的台阶总共有多少种跳法。

  其实,简单理解一下,题目二可以抽象为求一个斐波那契数列的第n项,与题目一的代码实现一致。

二、解题思路

  暂略。(此处主要作为书中python实现补充)

三、代码实现

  这里实现两个版本,包括 循环版本递归版本。后面简单做了对比实现,可以看出两种方式的计算效率有显著差距,具体请往下看。

  循环方式实现:(时间复杂度为 O ( n ) O(n) O(n),空间复杂度为 O ( 1 ) O(1) O(1)

def Fabonacci_loop(n):
	# 初始化
    temp_result_0 = 0
    temp_result_1 = 1
    fibN = 0
    
    if n == 0:
        return temp_result_0
    elif n == 1:
        return temp_result_1
    
    for i in range(2,n+1):
        fibN = temp_result_0 + temp_result_1
        temp_result_0 = temp_result_1
        temp_result_1 = fibN    
    return fibN

  递归方式实现:

def Fabonacci_recur(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    return Fabonacci_recur(n-1)+Fabonacci_recur(n-2)

  这里使用了一个小的 trick,由于循环版本耗时太短,记录不到,所以先计算1000次,然后将总的时间除以1000,即可得到平均每次的时间。

>>> import time
>>> time_start = time.time()
>>> for i in range(1000):
    	Fabonacci_loop(38)
>>> time_end = time.time()
>>> print("The time of loop :",(time_end-time_start)/1000)
Out:
The time of loop : 1.994609832763672e-06

  可以看出,采用上面的方式实现,耗时为 1.994609832763672e-06 s,而采用下面递归的方式实现,耗时为 13.88786005973816 s。因此,从这里我们在一定程度上体会到递归方式的缺点所在。

>>> time_start = time.time()
>>> Fabonacci_recur(38)
>>> time_end = time.time()
>>> print("The time of recur :",time_end-time_start)
Out:
The time of recur : 13.88786005973816
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值