斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。

n<=39

这个题可以说是迭代(Iteration) VS 递归(Recursion),
f(n) = f(n-1) + f(n-2),第一眼看就是递归啊,简直完美的递归环境,递归肯定很爽,这样想着关键代码两三行就搞定了,注意这题的n是从0开始的:

方法一:递归

1
2
3
4
5
6
7
8
9
10
if (n<= 1 ){
     return n;
}
int [] record =  new int [n+ 1 ];
record[ 0 ] =  0 ;
record[ 1 ] =  1 ;
for ( int i= 2 ;i<=n;i++){
     record[i] = record[i- 1 ] + record[i- 2 ];
}
return record[n];
虽然看起来很蠢,空间浪费了sizeof(int)*(n-1),但是对于那个超大n的测试用例应该是可以通过了,时间复杂度也达到了O(n)。

方法二:非递归

public class Solution {
     public int Fibonacci( int n) {
         int a= 1 ,b= 1 ,c= 0 ;
         if (n< 0 ){
             return 0 ;
         } else if (n== 1 ||n== 2 ){
             return 1 ;
         } else {
             for ( int i= 3 ;i<=n;i++){
                 c=a+b;
                 b=a;
                 a=c;
             }
             return c;
         }
     }
}


猜你喜欢

转载自blog.csdn.net/boguesfei/article/details/80588971