N-th Tribonacci Number
The task here is to find the n
-th number in the Tribonacci sequence, which is a series where each number is the sum of the three preceding numbers, starting from 0, 1, and 1.
|
|
Explanation
- If
n
is 0, 1, or 2, we directly return the corresponding value from the sequence definition. - We initialize a list with the first three Tribonacci numbers.
- Then, we use a
for
loop to calculate the Tribonacci numbers from the 3rd to then
-th number. - We store the numbers in the list
tribonacci_numbers
so that we can reuse them in subsequent calculations. - Finally, we return the
n
-th number from the list.
This approach ensures that we only calculate each Tribonacci number once and then store it for future use, leading to efficient computation.
title: N-th Tribonacci Number tags: recursion memoization
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
Constraints
- 0 <= n <= 37
The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.
Thinking Process
- Make an array F of length 38, and set F[0] = 0, F[1] = F[2] = 1.
- Now write a loop where you set F[n+3] = F[n] + F[n+1] + F[n+2], and return F[n].
Base cases
T0 = 0 for n = 0
T1 = 1 for n = 1
T2 = 1 for n = 2
Recurrence Relation
Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
T_3 = 0 + 1 + 1 = 2 n = 3
T_4 = 1 + 1 + 2 = 4 n = 4
- Recursive approach. Base cases, recurrence relation.
- Naive recursive approach: TLE
- Memoize
Naive Implementation
|
|
Optimized Solution
|
|