Algo-Sim › Recursion & Backtracking
Fibonacci Number
Easy · Recursion & Backtracking · step through it in Java, Python and C++ on your own input
Compute fib(n) with plain recursion and see how the call tree branches and repeats work.
Problem
The Fibonacci numbers start F(0) = 0, F(1) = 1, and each later one is the sum of the two before it. Given n, return F(n). This lesson computes it with plain recursion to show how the calls repeat.
Constraints
- 0 ≤ n ≤ 30
- Plain recursion makes about φⁿ calls, which is why memoization exists
Edge cases to test
- n = 0 and n = 1 (the base cases)
- Large n: the call tree doubles each level
- Negative n: reject it
Follow-up questions
- How do you make it O(n)?
- Memoise each fib(k) or fill a table bottom-up; keeping only the last two values makes it O(1) space.
- Can it be O(log n)?
- Raise the matrix [[1, 1], [1, 0]] to the n-th power with fast exponentiation: O(log n) multiplications.
Solution
Java
int fib(int n) {
if (n <= 1) {
return n;
}
int left = fib(n - 1);
int right = fib(n - 2);
return left + right;
}Python
def fib(n):
if n <= 1:
return n
left = fib(n - 1)
right = fib(n - 2)
return left + rightC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int fib(int n) {
if (n <= 1) {
return n;
}
int left = fib(n - 1);
int right = fib(n - 2);
return left + right;
}
};
More Recursion & Backtracking problems
- Tower of Hanoi (Medium)
- Generate Parentheses (Medium)
- Subsets (Medium)
- Subsets II (Medium)
- Permutations (Medium)
- Permutations II (Medium)
- Combinations (Medium)
- Letter Combinations of a Phone Number (Medium)
- Combination Sum (Medium)
- Combination Sum II (Medium)
- Palindrome Partitioning (Medium)
- Restore IP Addresses (Medium)
- Word Break II (Hard)
- Remove Invalid Parentheses (Hard)
- Word Search (Medium)
- N-Queens (Hard)
- Sudoku Solver (Hard)