《剑指offer》1: 斐波那契数列

题目描述

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

n<=39

 

这个题目大家在学编程的时候都应该遇到过,但是不能够使用递归解法,因为如果使用递归,就会超出时间,算法的复杂度是2^n。因此这里采用迭代的解法。

代码如下所示:

# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        if n==1:
        
            return 1
        if n==0:
            return 0

        a=1
        b=0
        ret=0
     #下面range表示循环进行的次数,输入n=3,就循环2次,输入4就循环3次
for i in range(0,n-1): ret=a+b b=a a=ret return ret

 

posted @ 2020-08-03 21:01  Geeksongs  阅读(227)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.