斐波那契数列

斐波那契数列

题目描述

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

n<=39

循环比递归效率高, 这时因为递归还需要压栈出栈
版本一使用直接递归, 版本二相对版本一修改一些判断条件不知道为什么在牛客上一直提交不了, 版本四使用循环, 版本四为书上的斐波那契数列方法

版本一:直接递归, 最开始想到的牛(慢)一样的方法

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

版本二: 牛客提交表示超时

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

版本三: 使用循环方法

class Solution {
public:
    int Fibonacci(int n) {
        int fn_1 = 1;
        int fn_2 = 0;
        int ret = 0;
        
        if (n <= 0) {
            return 0;
        }
        else if (1 == n) {
            return 1;
        }
        else {
            for (int i = 2; i <= n; i++) {
                ret = fn_1 + fn_2;
                fn_2 = fn_1;
                fn_1 = ret;
            }
            return ret;
        }
    }
};

版本四: 书上标准递归方法求斐波那契数列

long long Fibonacci(unsigned int n) {
	if (n <= 0) {
		return 0;
	}
	if (1 == n) {
		return 1;
	}

	return (Fibonacci(n - 1) + Fibonacci(n - 2));
}
原文地址:https://www.cnblogs.com/hesper/p/10422366.html