The Tribonacci sequence Tn is defined as follows:
T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
Given n
, return the value of Tn.
Example 1:
Input: n = 4
Output: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
Example 2:
Input: n = 25
Output: 1389537
n
?
n
is 0 <= n <= 37.To solve this problem, we have a few approaches:
n
. This approach is efficient and avoids the overhead of recursion.n
.Given that n
can go up to 37, we will use the dynamic programming approach for an efficient solution.
def tribonacci(n: int) -> int:
# Base cases
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
# Initialize the base values
trib = [0] * (n + 1)
trib[0] = 0
trib[1] = 1
trib[2] = 1
# Fill the tribonacci series values up to nth
for i in range(3, n + 1):
trib[i] = trib[i - 1] + trib[i - 2] + trib[i - 3]
return trib[n]
# Example usage:
print(tribonacci(4)) # Output: 4
print(tribonacci(25)) # Output: 1389537
n
is 0, 1, or 2 directly by returning their known values.trib
where trib[i]
holds the value of the i-th Tribonacci number.trib[i]
using the formula trib[i] = trib[i - 1] + trib[i - 2] + trib[i - 3]
.trib[n]
as the result.By following this approach, we ensure that we compute the Tribonacci number efficiently and within optimal time and space complexity.
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?