每日一道算法题——斐波那契数列Fibonacci

题目:

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1),n≤39;

示例1

输入:

4

返回值:

3

代码:

方法一:递归

public class Solution {
    public int Fibonacci(int n) {
        if(n==0){
            return 0;
        }
        if(n==1){
            return 1;
        }
        return Fibonacci(n-1)+Fibonacci(n-2);
    }
}

运行时间:851ms

方法二:

public class Solution {
    public int Fibonacci(int n) {
       int[] arr = {0,1};
        if(n<2){
           return arr[n];
        }
        int frist = 0;
        int second =1;
        int total = 0;
        for(int i= 2;i<=n;i++){
            total = frist + second;
            frist = second;
            second = total;
        }
        return total;
    }
}

运行时间:11ms

总结:使用递归确实会增加应用程序的负担,要慎重使用;有时使用书写相对复杂的循环效果可能会更好!

原文地址:https://www.cnblogs.com/jiangbaoyabo/p/14516774.html