N-th Tribonacci Number
Difficulty: Easy · Pattern: 1-D Dynamic Programming · LeetCode #1137
T0 = 0, T1 = 1, T2 = 1, and T(n+3) = T(n) + T(n+1) + T(n+2). Return Tn.
Examples
text
n = 4 → 4
n = 25 → 1389537Hints
- Same as Fibonacci, but each term depends on the last three.
Approach
Keep a, b, c and roll them forward: a, b, c = b, c, a + b + c. It's O(n) time and O(1) space. A recurrence of order k needs k rolling variables.
Complexity
Time: O(n). Space: O(1).
Python solution
def tribonacci(n):
a, b, c = 0, 1, 1
for _ in range(n):
a, b, c = b, c, a + b + c
return aJavaScript solution
function tribonacci(n) {
let a = 0, b = 1, c = 1;
for (let i = 0; i < n; i++) [a, b, c] = [b, c, a + b + c];
return a;
}