Categories
Dynamic Programming Leetcode Recursion

Fibonacci (Recursion)

function fib(x) {
    let cache = {}
    function fibInternal(n) {
        if(n == 0) return 0;
        if(n <= 2) return 1;
        if (cache[n]) return cache[n];

        const result = fibInternal(n - 1) + fibInternal(n - 2);
        cache[n] = result;
        return result;
    }

    return fibInternal(x)
}

Leave a Reply

Your email address will not be published. Required fields are marked *