The Tribonacci sequence T(n) is defined as follows:
T(0) = 0, T(1) = 1, T(2) = 1, and T(n+3) = T(n) + T(n+1) + T(n+2) for n >= 0.
Given n
, return the value of T(n).
n
?
To solve this problem efficiently, we can use dynamic programming. Specifically, we can build the Tribonacci sequence iteratively from the base cases up to n
. This avoids the exponential time complexity of a naive recursive implementation.
n
and use the known values T(i) = T(i-1) + T(i-2) + T(i-3).Here is the C++ implementation of the above strategy:
#include <iostream>
using namespace std;
class Solution {
public:
int tribonacci(int n) {
if (n == 0) return 0;
if (n == 1 || n == 2) return 1;
int t0 = 0, t1 = 1, t2 = 1;
int t3;
for (int i = 3; i <= n; ++i) {
t3 = t0 + t1 + t2;
t0 = t1;
t1 = t2;
t2 = t3;
}
return t3;
}
};
// Example usage
int main() {
Solution solution;
int n = 25; // Example input
cout << "T(" << n << ") = " << solution.tribonacci(n) << endl;
return 0;
}
The time complexity of this solution is O(n) because we compute each value of the Tribonacci sequence up to n
exactly once.
The space complexity of this solution is O(1) due to the optimization where only a constant amount of extra space is used for the three variables tracking the last three Tribonacci numbers.
This approach ensures both efficiency and clarity, making it suitable for typical constraints on LeetCode.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?