File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .HashMap ;
2+
3+ public class Fibonacci {
4+
5+ // Create a memoization HashMap to store computed Fibonacci values
6+ private static HashMap <Integer , Integer > memo = new HashMap <>();
7+
8+ public static void main (String [] args ) {
9+ int n = 16 ;
10+ System .out .println ("Fib(" + n + ") : " + fibonacci (n ));
11+ }
12+
13+ public static int fibonacci (int n ) {
14+ if (n <= 1 ) {
15+ return 1 ;
16+ }
17+
18+ // Check if the value is already computed and stored in the memoization HashMap
19+ if (memo .containsKey (n )) {
20+ return memo .get (n );
21+ }
22+
23+ // Calculate Fibonacci recursively and store the result in memoization
24+ int result = fibonacci (n - 1 ) + fibonacci (n - 2 );
25+ memo .put (n , result );
26+
27+ return result ;
28+ }
29+ }
You can’t perform that action at this time.
0 commit comments