Fibonacci with Memoization
Problem
Print the n-th Fibonacci number, where F(0) = 0, F(1) = 1 and F(n) = F(n-1) + F(n-2). Use recursion with a memo table so that each value is computed once.
Constraints
- 0 <= n <= 70
Examples
Input
10
Output
55
Solutions
Plain recursion calls the same values again and again, so it takes O(2^n) time. A memo table makes each F(i) run once, which gives O(n). F(70) is below 2^53, so it is exact in JavaScript.
/*
* Problem : Fibonacci.
* Input : One integer n.
* Output : F(n).
* Approach: Recursion with memo.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: memo[i] stores F(i) after we compute it. 0 means "not computed yet" (F(i) is never 0 for i >= 1).
static long fibonacci(int n, long[] memo) {
// Step 2: Base cases.
if (n < 2) {
return n;
}
// Step 3: If we have the answer, use it. Otherwise compute it once and save it.
if (memo[n] == 0) {
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
}
return memo[n];
}
// This method solves the task. It receives the input and returns the answer.
static long solve(long n) {
return fibonacci((int) n, new long[(int) n + 2]);
}
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong();
System.out.println(solve(n));
}
}
Hints (1)
- Why is plain recursion slow here?