509.Fibonacci Number(搬运LeetCode官方解)

题解:
1.Top-Down Approach using Memoization(自顶向下备忘录法)

Check if N <= 1. If it is, return N.
Call and return memoize(N)
If N exists in the map, return the cached value for N
Otherwise set the value of N, in our mapping, to the value of memoize(N-1) + memoize(N-2)

如求f(5),则本应调用f(4)和f(3),但求f(4)的过程中也会把f(3)求出来,保存在备忘录中,所以求f(5)时就不需要再次调用f(3),直接返回f(3)的值,即catch[3]

class Solution {
    private Integer[] cache = new Integer[31];//定义一个存放斐波那契数的数组

    public int fib(int N) {
        if (N <= 1) {
            return N;
        }
        cache[0] = 0;
        cache[1] = 1;
        return memoize(N);
    }

    public int memoize(int N) {
      if (cache[N] != null) {	
          return cache[N]; //如果某个N对应的斐波那契数已经求过了,那直接返回该数,不用再进入该N对应的递归树中
      }
      cache[N] = memoize(N-1) + memoize(N-2);
      return memoize(N); //用备忘录记录求过的解
    }
}

2.Bottom-Up Approach using Memoization
Algorithm

If N is less than or equal to 1, return N
Otherwise, iterate through N, storing each computed answer in an array along the way.
Use this array as a reference to the 2 previous numbers to calculate the current Fibonacci number.
Once we’ve reached the last number, return it’s Fibonacci number.

如想求出N=5时对应的斐波那契数,则从N=1时开始求起f(1),f(2)…一直求到f(5)

class Solution {
    public int fib(int N) {
        if (N <= 1) {
            return N;
        }
        return memoize(N);
    }

    public int memoize(int N) {
      int[] cache = new int[N + 1];
      cache[1] = 1;

      for (int i = 2; i <= N; i++) {
          cache[i] = cache[i-1] + cache[i-2];
      }
      return cache[N];
    }
}

3.Iterative Top-Down Approach

class Solution {
    public int fib(int N) {
        if (N <= 1) {
            return N;
        }
        if (N == 2) {
            return 1;
        }

        int current = 0;
        int prev1 = 1;
        int prev2 = 1;

        for (int i = 3; i <= N; i++) {
            current = prev1 + prev2;
            prev2 = prev1;
            prev1 = current;
        }
        return current;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值