1137. N-th Tribonacci Number #219
-
Topics: 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 Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The Tribonacci sequence is a variation of the Fibonacci sequence, where each number is the sum of the previous three numbers. In this problem, you're tasked with calculating the N-th Tribonacci number using the given recurrence relation:
The goal is to compute Tn efficiently, considering the constraints 0 ≤ n ≤ 37. Key Points
Approach
Plan
Let's implement this solution in PHP: 1137. N-th Tribonacci Number <?php
/**
* @param Integer $n
* @return Integer
*/
function tribonacci(int $n): int
{
$dp = [0, 1, 1];
for ($i = 3; $i < $n + 1; $i++) {
$dp[$i % 3] = array_sum($dp);
}
return $dp[$n % 3];
}
// Example usage:
$n1 = 4;
$n2 = 25;
echo tribonacci($n1) . "\n"; // Output: 4
echo tribonacci($n2) . "\n"; // Output: 1389537
?> Explanation:
Example WalkthroughInput: n = 4
Output: 4Time Complexity
Output for Example
The optimized solution efficiently calculates the N-th Tribonacci number using a space-optimized dynamic programming approach. It ensures both correctness and performance, adhering to the constraints provided in the problem. |
Beta Was this translation helpful? Give feedback.
The Tribonacci sequence is a variation of the Fibonacci sequence, where each number is the sum of the previous three numbers. In this problem, you're tasked with calculating the N-th Tribonacci number using the given recurrence relation:
The goal is to compute Tn efficiently, considering the constraints 0 ≤ n ≤ 37.
Key Points