斐波那契数列

你们都知道斐波那契数列,如今要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。java

n<=39数组

 

1. 递归法

1. 分析

斐波那契数列的标准公式为:F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>=3,n∈N*)
根据公式能够直接写出:优化

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

3. 复杂度

时间复杂度:O(2^n)
空间复杂度:O(1)spa

2. 优化递归

1. 分析

递归会重复计算大量相同数据,咱们用个数组把结果存起来8!code

2. 代码

public class Solution {
    public int Fibonacci(int n) {
        int ans[] = new int[40];
        ans[0] = 0;
        ans[1] = 1;
        for(int i=2;i<=n;i++){
            ans[i] = ans[i-1] + ans[i-2];
        }
        return ans[n];
    }
}

 

3. 复杂度:

时间复杂度:O(n)
空间复杂度:O(n)递归

3. 优化存储

1. 分析

其实咱们能够发现每次就用到了最近的两个数,因此咱们能够只存储最近的两个数ci

  • sum 存储第 n 项的值
  • one 存储第 n-1 项的值
  • two 存储第 n-2 项的值

2. 代码

public class Solution {
    public int Fibonacci(int n) {
        if(n == 0){
            return 0;
        }else if(n == 1){
            return 1;
        }
        int sum = 0;
        int two = 0;
        int one = 1;
        for(int i=2;i<=n;i++){
            sum = two + one;
            two = one;
            one = sum;
        }
        return sum;
    }
}

3. 复杂度:

时间复杂度:O(n)
空间复杂度:O(1)io

相关文章
相关标签/搜索