N-th Tribonacci Number LeetCode solution in JavaScript

1
// Recursive and Memoiztion approach
2
var tribonacci = function (n, cache = {}) {
3
if (n in cache) return cache[n];
4

5
//Start of Base Cases
6
if (n == 0) return 0;
7
if (n == 1 || n == 2) return 1;
8
// End Of Base Cases
9

10
// Caching the result
11
cache[n] =
12
tribonacci(n - 1, cache) +
13
tribonacci(n - 2, cache) +
14
tribonacci(n - 3, cache);
15

16
return cache[n];
17
};
18

19
// Tabulation Approach
20
var tribonacci = function (n) {
21
// Create the Table;
22
const table = Array(n + 1).fill(0);
23
table[1] = 1;
24
for (let i = 0; i <= n; i++) {
25
//Iterate over the table and increase the values respectively
26
table[i + 1] += table[i];
27
table[i + 2] += table[i];
28
table[i + 3] += table[i];
29
}
30
return table[n];
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0