Quick actions

cmd+k|ctrl+k

Navigation

Languages

Fibonacci memorization DP

Snippet info

Language

Java

Visibility

public

Author

devernul

Created

2018-12-11T03:42:03Z

Updated

2018-12-11T03:42:21Z

import java.util.HashMap;
class Main {
    public static void main(String[] args) {
        System.out.println(fibonacci(12));
    }
    
    
    public static int fibonacci(int n) {
        HashMap<Integer, Integer> cache = new HashMap<Integer, Integer>();
        return fibonacciRec(n, cache);
    }

    private static int fibonacciRec(int n, HashMap<Integer, Integer> cache){
        if (n < 1) return 1;
        if (cache.containsKey(n))return cache.get(n);
        else {
            int res = fibonacciRec(n - 1, cache) + fibonacciRec(n - 2, cache);
            cache.put(n, res);
            return res;
        }
    }
}
INFO