We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Implementation with cache to reduce redundant calculations and help with response times.
static Map cache = new HashMap();
public static int fibonacci(int n) {
if(n==0) return 0;
if(n==1) return 1;
if(cache.get(n) != null) return (int) cache.get(n);
int a = fibonacci(n-1);
int b = fibonacci(n-2);
cache.put(n-1,a);
return a+b;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Recursion: Fibonacci Numbers
You are viewing a single comment's thread. Return to all comments →
Implementation with cache to reduce redundant calculations and help with response times.
static Map cache = new HashMap();
public static int fibonacci(int n) { if(n==0) return 0; if(n==1) return 1; if(cache.get(n) != null) return (int) cache.get(n); int a = fibonacci(n-1); int b = fibonacci(n-2); cache.put(n-1,a); return a+b; }