刷题笔记7——输出斐波那契数列的第n项

题目描述

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
刷题笔记7——输出斐波那契数列的第n项_第1张图片

1、递归

class Solution {
public:
    int Fibonacci(int n) {
        int num[39];
        num[0] = 0;
        num[1] = 1;
        int cnt = 2;
        while(cnt <= n) {
            num[cnt] = num[cnt - 1] + num[cnt - 2];
            cnt++;
        }
        
        return num[n];
    }
};

2、常规方法

class Solution {
public:
    int Fibonacci(int n) {
        if(0 == n)
            return 0;
        if(1 == n)
            return 1;
        
        int first = 0;
        int second = 1;
        int res = 1;
        for(int cnt = 2; cnt < n; ++cnt) {
            first = second;
            second = res;
            res = first + second;
        }
        
        return res;
    }
};

你可能感兴趣的:(刷题)