LeetCode刷题之509 Fibonacci Number

1. Description

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

  • F(0) = 0, F(1) = 1
  • F(n) = F(n - 1) + F(n - 2), for n > 1.

Given n, calculate F(n).

2.Test Cases

Example 1:

Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.

Example 2:

Input: n = 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.

Example 3:

Input: n = 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.

3. Solution

3.1 暴力递归

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

Runtime: 5 ms, faster than 31.54% of Java online submissions for Fibonacci Number.
Memory Usage: 35.5 MB, less than 66.51% of Java online submissions for Fibonacci Number.

3.2 带备忘录递归

这里递归最大的问题在于重复计算,如果重复的部分只计算一次,那么会大大提高效率。

class Solution {
    public int fib(int n) {
        if (n ==0 ) return 0;
        int[] res = new int[n + 1];
        
        return helper(res, n );
    }
    
    private int helper(int[] res , int n) {
        if( n ==1 || n == 2) return 1;
        if (res[n] != 0) return res[n];
        return helper(res, n - 1) + helper(res, n-2);
    }
}

Runtime: 8 ms, faster than 17.26% of Java online submissions for Fibonacci Number.
Memory Usage: 36 MB, less than 6.98% of Java online submissions for Fibonacci Number.
这个很迷,我以为会变快来着。。。谁可以给我解答一下??

3.3 动态规划

自底向上推算。

class Solution {
    public int fib(int n) {
        if (n ==0 ) return 0;
        if (n ==1 ) return 1;
        int[] res = new int[n + 1];
        
        res[2]= res[1] = 1;
        for (int i = 3; i <= n; i++) {
            res[i] = res[i - 1 ] + res[i - 2];
        }
        return res[n];   
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Fibonacci Number.
Memory Usage: 35.8 MB, less than 32.52% of Java online submissions for Fibonacci Number.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值