斐波那契数列

时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M 

题目描述

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

n<=39

思路:

  首先想到的肯定是使用递归

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

 接着采用递推的方式,使用循环计算斐波那契数列

class Solution {
public:
    int Fibonacci(int n) {
        int fn1 = 1;
        int fn2 = 1;
        if(n <= 0)
        {
            return 0;
        }
        if(n == 1|| n ==2)
        {
            return 1;
        }
        while(n-- > 2)
        {
            fn1 = fn1 + fn2;
            fn2 = fn1 - fn2;
        }
        return fn1;
    }
};

后来又在网上看到了另一种解法,使用动态规划的方法来做的(但我并没有运行成功,总是说我没有初始化,但理论感觉还是行得通的,所以记录下)

class Solution {
public:
    int Fibonacci(int n) {
        if(n <= 1)
            return 1;
        int step[] = new int[n+1];
     int *step = new int[n+1](); step[
0] = 0; step[1] = 1; for(int i = 2;i < n;i++) { step[i] = step[i-2] + step[i - 1]; } return step[n]; } };

 

 

原文链接: https://www.cnblogs.com/whiteBear/p/12433680.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    斐波那契数列

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/333929

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午9:25
下一篇 2023年3月1日 下午9:25

相关推荐