C++フィボナッチ数列を実現

1022 ワード

#include 

using namespace std;

//             
/*
            ,          ,          ,         !
       :       ,                  !              ,            
          ,                :             !                      ,            
       。            ,              ,                      ,                。

    :                  ,                   ,             !
*/

class Solution{
public:
    //       
    int FibByRecursive(int n){
        if(n <= 0){
            return 0;
        }

        if(n == 1){
            return 1;
        }

        return FibByRecursive(n-1) + FibByRecursive(n-2);
    }
    //       
    int Fib(int n){
        if(n <= 0){
            return 0;
        }
        if(n == 1){
            return 1;
        }

        int first=0, second=1, third = 0;
        for(int i=2; i <= n; i++){
            third = first + second;
            second = first;
            third = second;
        }
        return third;
    }
};