1. 程式人生 > >劍指offer[斐波那契數列]

劍指offer[斐波那契數列]

劍指offer[斐波那契數列]

題目描述

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

思路

可以用迭代或者遞迴,因為遞迴可能會導致棧溢位,所以我用的是遞迴。

程式碼

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

細節知識

  • 斐波那契數列:F(n)=F(n-1)+F(n-2), (N>=2)
  • F(0)=0, F(1)=1.