1. 程式人生 > >刷題筆記7——輸出斐波那契數列的第n項

刷題筆記7——輸出斐波那契數列的第n項

題目描述

大家都知道斐波那契數列,現在要求輸入一個整數n,請你輸出斐波那契數列的第n項(從0開始,第0項為0)。
n<=39
在這裡插入圖片描述

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; } };