Skip to content

Commit c6d8eb7

Browse files
authored
Create FibonacciMemoization.java
1 parent 513070d commit c6d8eb7

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/java/FibonacciMemoization.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

0 commit comments

Comments
 (0)