求裴波那切数列的第n项

1.题目

写入一个函数,输入n,输出裴波那切数列的第n项

2.思路

递归–时间和空间复杂度高
循环–时间和空间复杂度低,通过循环迭代计算第n项,首先根据f(0)和f(1)计算f(2),在根据f(1)和f(2)计算f(3),依次类推计算出第n项。

 class Solution {
public:
    int Fibonacci(int n) {
        // n==0
        if(n<=0)
            return 0;

        // n==1
        if(n==1)
            return 1;

        // n>1
        int one=0;
        int two=1;
        int three=0;

        for(int i = 2;i<=n;i++){
            three = one + two;
            one =two;
            two = three;
        }
        return three;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_35433716/article/details/81837229