(Java)斐波那契数列

(Java)斐波那契数列

题目:

斐波那契数列(黄金分割数列、兔子数列)
数列:0、1、1、2、3、5、8、13、21、34、······
斐波那契数列递推公式:
F(1) = 1, F(2) = 1, F(n) = F(n-1)+F(n-2) (n>=3,n是正整数)
要求:输入一个整数n,输出斐波那契数列的第n项(从0开始,第0项为0,第1项为1)。(n<=39)

题解一(递归):

import java.util.*;
public class Fibonacci {
    public static void main(String [] args)
    {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        System.out.println(fibonacci(n));
    }
    public static int fibonacci(int n)
    {
        if (n==0)
            return 0;
        else if (n==1)
            return 1;
        else
            return fibonacci(n-1)+fibonacci(n-2);
    }

}

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

题解二:

用递归的方法可以发现有很多重复计算的地方,所以我们可以建立一个数组,把每次计算的结果存起来,这样就可以避免重复计算。

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];
    }
}

时间复杂度O(n)
空间复杂度O(n)

题解三:

每次计算的时候,我们只需要前面两个数的值,所以用两个变量把前面的值记下来就行,不需要记下整个数组。

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值