1137. N-th Tribonacci Number
Problem
The Tribonacci sequence is T₀ = 0, T₁ = 1, T₂ = 1 and Tₙ₊₃ = Tₙ + Tₙ₊₁ + Tₙ₊₂. Return Tₙ.
Example: n = 4 → 4; n = 25 → 1389537
Constraints: n ≤ 37.
Fibonacci with three terms: keep a rolling window (a, b, c) and slide it n times.
Complexity: O(n) time, O(1) space.
class Solution:
def tribonacci(self, n: int) -> int:
a, b, c = 0, 1, 1
for _ in range(n):
a, b, c = b, c, a + b + c
return a
assert Solution().tribonacci(4) == 4
assert Solution().tribonacci(25) == 1389537
assert [Solution().tribonacci(i) for i in range(4)] == [0, 1, 1, 2]
assert Solution().tribonacci(37) == 2082876103
class Solution {
public int tribonacci(int n) {
int a = 0, b = 1, c = 1;
for (int i = 0; i < n; i++) { int d = a + b + c; a = b; b = c; c = d; }
return a;
}
}
func tribonacci(n int) int {
a, b, c := 0, 1, 1
for i := 0; i < n; i++ {
a, b, c = b, c, a+b+c
}
return a
}