Skip to content

Commit 48b3a05

Browse files
Merge pull request #13 from lxmn22nov/lxmn3
Java: Memoization
2 parents 8151a36 + ff44b1d commit 48b3a05

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
* PROBLEM: 1137
3+
*
4+
* The Tribonacci sequence Tn is defined as follows:
5+
6+
T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
7+
8+
Given n, return the value of Tn.
9+
10+
Example 1:
11+
Input: n = 4
12+
Output: 4
13+
Explanation:
14+
T_3 = 0 + 1 + 1 = 2
15+
T_4 = 1 + 1 + 2 = 4
16+
17+
Example 2:
18+
Input: n = 25
19+
Output: 1389537
20+
*/
21+
public class NthTribonacciNumber {
22+
public int tribonacci(int n) {
23+
if (n <= 2) {
24+
return n == 0 ? 0 : 1;
25+
}
26+
int[] dp = new int[n + 1];
27+
dp[1] = dp[2] = 1;
28+
for (int i = 3; i <= n; i++) {
29+
dp[i] = dp[i - 2] + dp[i - 1] + dp[i - 3];
30+
}
31+
return dp[n];
32+
}
33+
}

0 commit comments

Comments
 (0)