Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9ccb109

Browse files
algorithms/src/main/java/ivanmarkovic/algorithms/recursion/FibonacciMemoization.java
1 parent 9e11491 commit 9ccb109

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package ivanmarkovic.algorithms.recursion;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
public class FibonacciMemoization {
7+
8+
9+
private static Map<Integer, Integer> memo = new HashMap<>();
10+
11+
public static void main(String args[]) {
12+
for(int i = 1; i <= 6; i++)
13+
System.out.println("Fibonacci " + i + " is " + fibonacci(i));
14+
}
15+
16+
public static int fibonacci(int n) {
17+
if(n == 1)
18+
return 0;
19+
else if (n == 2)
20+
return 1;
21+
else {
22+
if(!memo.containsKey(n)) {
23+
int f = fibonacci(n - 1) + fibonacci(n - 2);
24+
memo.put(n, f);
25+
}
26+
return memo.get(n);
27+
}
28+
}
29+
30+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /