【剑指offer】菲波那切数列Java实现

题目

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

  • 输入 4
  • 返回值 3

一 递归实现

    public static void main(String[] args) {
        int inputNum = 39;
        System.out.println(Fibonacci(inputNum));
    }

    /**
     * 递归实现
     * 时间复杂度 O(n方)
     * 空间复杂度 O(1)
     *
     * @param n
     * @return
     */
    public static int Fibonacci(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        return Fibonacci(n - 1) + Fibonacci(n - 2);
    }
  • 时间复杂度 O(n²)
  • 空间复杂度:O(1)

二 优化递归

    static HashMap<Integer, Integer> hashMap = new HashMap<>();

    /**
     * 优化递归调用 记录每次算出的和给后面计算使用
     *
     * @param n
     * @return
     */
    public static int Fibonacci1(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;

        int left1;
        int pos1 = n - 1;
        if (hashMap.get(pos1) != null && hashMap.get(pos1) > 0) {
            left1 = hashMap.get(pos1);
        } else {
            left1 = Fibonacci(pos1);
            hashMap.put(pos1, left1);
        }

        int left2;
        int pos2 = n - 2;
        if (hashMap.get(pos2) != null && hashMap.get(pos2) > 0) {
            left2 = hashMap.get(pos2);
        } else {
            left2 = Fibonacci(pos2);
            hashMap.put(pos2, left2);
        }

        return left1 + left2;
    }
  • 时间复杂度 O(n)
  • 空间复杂度:O(n)

三 优化存储

    public static int Fibonacci2(int n) {
        int[] nums = new int[40];
        nums[0] = 0;
        nums[1] = 1;
        for (int i = 2; i <= n; i++) {
            nums[i] = nums[i - 1] + nums[i - 2];
        }
        return nums[n];
    }
  • 时间复杂度 O(n)
  • 空间复杂度:O(n)

四 持续优化

    /**
     * 时间复杂度 O(n)
     * 空间复杂度 O(1)
     *
     * @param n
     * @return
     */
    public static int Fibonacci3(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        int sum = 0; //当前存储的第n项的值
        int a = 1; //当前n-1的值
        int b = 0;//当前n-2的值
        for (int i = 2; i <= n; i++) {
            sum = a + b;
            b = a;
            a = sum;
        }
        return sum;
    }
  • 时间复杂度 O(n)
  • 空间复杂度:O(1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值