-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTribnocci.java
More file actions
30 lines (24 loc) · 774 Bytes
/
Copy pathTribnocci.java
File metadata and controls
30 lines (24 loc) · 774 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package DynamicProgramming;
import java.util.HashMap;
public class Tribnocci {
public static void main(String[] args) {
int n = 4;
HashMap<Integer, Integer> memo = new HashMap<>();
int result = tribonnci(n, memo);
System.out.println("The " + n + "th Tribonacci number is: " + result);
}
public static int tribonnci(int index, HashMap<Integer, Integer> mem) {
if (index <= 1) {
return 0;
}
if (index == 2) {
return 1;
}
if (mem.containsKey(index)) {
return mem.get(index);
}
int val = tribonnci(index - 1, mem) + tribonnci(index - 2, mem) + tribonnci(index - 3, mem);
mem.put(index, val);
return val;
}
}