14.29 Fibonacci Sequence
14.29.1 Problem Metadata
- Platform: Firecode.io / Classic
- Problem ID: Fibonacci
- Difficulty: Level 2
- URL: https://www.firecode.io/
- Tags:
- Techniques: Recursion, Dynamic Programming, Memoization, Tabulation
14.29.2 Description
Compute the n-th Fibonacci number where F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2).
14.29.6 Solution 2 - Tail Recursion
14.29.6.1 Walkthrough
Carry two consecutive Fibonacci values forward so each call decrements n until reaching zero. Although still recursive, it avoids repeated subproblems.
14.29.7 Solution 3 - Bottom-Up DP
14.29.8 Solution 4 - Memoized Recursion
14.29.8.1 Walkthrough
Use a memo array to cache computed Fibonacci numbers, preventing redundant recursion.
14.29.8.3 Code - Java
public int fibMemo(int n) {
int[] memo = new int[n + 1];
Arrays.fill(memo, -1);
return fibMemoHelper(n, memo);
}
private int fibMemoHelper(int n, int[] memo) {
if (n <= 1) {
return n;
}
if (memo[n] != -1) {
return memo[n];
}
memo[n] = fibMemoHelper(n - 1, memo) + fibMemoHelper(n - 2, memo);
return memo[n];
}