剑指offer第七题(裴波那契数列)

来源:互联网 发布:修改sql触发器 编辑:程序博客网 时间:2024/06/15 05:03
题目:大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。

n<=39

斐波那契数列:斐波那契数列指的是这样一个数列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368........

斐波那契数列:1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
如果设F(n)为该数列的第n项(n∈N*),那么这句话可以写成如下形式::F(n)=F(n-1)+F(n-2)
注意事项:我直接使用递推公式存在复杂度问题,不能提交。

java代码:

public class Solution {
    public int Fibonacci(int n) {
        if(n<0){
            return 0;
        }
        else if (n==1) {
            return 1;
        }
        int result=0;
        int temp =0;
        int temp1=1;
        for(int i=2;i<=n;i++){
            result=temp+temp1;
            temp=temp1;
            temp1=result;
        }
        return result;
    }
}

python代码:

# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        if n<=0:
            return 0
        if n==1:
            return 1
        a=0
        b=1
        for i in range(2,n+1):
            result=a+b
            a=b
            b=result
        return result


原创粉丝点击