LeetCode-----フィボナッチ数列

4259 ワード

  • テーマ:
  •      ,   n ,     (Fibonacci)     n  。           :
    
    F(0) = 0,   F(1) = 1
    F(N) = F(N - 1) + F(N - 2),    N > 1.
            0   1   ,                     。
    
           1e9+7(1000000007),        :1000000008,    1。
    
     
    
      :  (LeetCode)
      :https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof
              。           ,          。
    
  • 解法1:再帰
  • class Solution {
    public:
        int fib(int n) {
    	if (n <= 1)
    	{
    		return n;
    	}
    	else
    	{
    		return fib(n - 1) + fib(n - 2);
    	}
        }
    };
    

    *解法2:
    class Solution {
    public:
        int fib(int n) {
    		if (n == 0 || n == 1)
    			return n;
    
    		int a = 1, b = 0;
    		for (int i = 1; i < n; i++) {
    			a = a + b;
    			b = a - b;
    			a %= 1000000007;
    		}
    		return a;
        }
    };