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

Edge cases to test

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 + right

C++

#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