Grokking the Art of Recursion for Coding Interviews
Vote
0% completed
Solution: Fibonacci Series Using Memoization
Problem Statement
Print Fibonacci Series Using Memoization and Recursion.
Given a positive integer n, print the Fibonacci series up to the nth term using memoization and recursion.
Examples:
| Sr# | Input | Output | Explanation |
|---|---|---|---|
| 1 | 5 | 0, 1, 1, 2, 3 | The Fibonacci series up to the 5th term is 0, 1, 1, 2, 3 |
.....
.....
.....
Like the course? Get enrolled and start learning!
G
Gaurav Rai Mazra
· 2 years ago
In question, it is asked to generate fibonacci series for n using memoization i.e.
public static List<Integer> fibonacci(int n);
whereas solution talks about generating n fibonacci using memoization i.e.
public static int fibonacci(int n);
The solution need to be updated as follows:
- Base case:
- n = 0
- return List.of(0);
- n = 1
- return List.of(0, 1);
- n > 1
- add 0 and 1 in result and recursive call to fibonacci generation.
- n = 0
public static List<Integer> fibonacci(int n) { if (n == 0) return List.of(0); if (n == 1) return List.of(0, 1); List<Integer> result = new ArrayList<>(); result.add(0); result.add(1); Map<Integer, Integer> cache = n