7、剑指offer - 斐波那契数列

考点:

递归和循环

题目描述:

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

解题:

递归:

class Solution {
public:
    int Fibonacci(int n) {
        if(n == 0){
            return 0;
        }else if(n == 1 || n == 2){
            return 1;
        }else{
            return Fibonacci(n-1) + Fibonacci(n-2);
        }
    }
};

非递归

class Solution {
public:
    int Fibonacci(int n) {
        if(n == 0){
            return 0;
        }else if(n == 1 || n == 2){
            return 1;
        }else{
            int first = 1;
            int second = 1;
            int result = 0;
            for(int i = 3;i <= n;i++){
                result = first + second;
                first = second;
                second = result;
            }
            return result;
        }
    }
};
发布了46 篇原创文章 · 获赞 62 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/qq_42250189/article/details/105591127