(java)leetcode509 斐波那契数列的常规解法及其改进(新增)

题目描述:

斐波那契数,一般用 F(n) 表示,造成的序列称为斐波那契数列。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是:html

F(0) = 0,   F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.

给定 N,计算 F(N)java

示例 1:code

输入:2
输出:1
解释:F(2) = F(1) + F(0) = 1 + 0 = 1.

示例 2:htm

输入:3
输出:2
解释:F(3) = F(2) + F(1) = 1 + 1 = 2.

示例 3:递归

输入:4
输出:3
解释:F(4) = F(3) + F(2) = 2 + 1 = 3.

提示:ci

  • 0 ≤ N ≤ 30

解题思路:

一、常规解法,直接递归调用实现get

二、改进解法,递归调用方法每一步都须要去计算,很浪费时间,能够提早将每一步的计算结果存下来,后面须要直接取用便可。io

代码实现:

class Solution {
    public int fib(int N) {
        if(N==0)
            return 0;
        if(N==1)
            return 1;
        return fib(N-1)+fib(N-2);
    }
}
class Solution {
    public int fib(int N) {
        List fabList = new ArrayList<Integer>();
        if(N==0){
            return 0;
        }else if (N==1){
            return 1;
        }else {
            fabList.add(0);
            fabList.add(1);
            for(int i=2;i<=N;i++){
                fabList.add((int)fabList.get(i-2) + (int)fabList.get(i-1));
            }
            return (int)fabList.get(N);
        }
    }
}

新增一种解法,只存储前两个值,占用更少的空间class

public class Solution {
    public int Fibonacci(int n) {
        if(n==0){
            return 0;
        }else if(n==1){
            return 1;
        }else{
            int temp1=0;
            int temp2=1;
            int temp3=0;
            for(int i=2;i<=n;i++){
                temp3=temp1+temp2;
                temp1=temp2;
                temp2=temp3;
            }
            
            return temp3;
        }
        
        
    }
}