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.