-
Notifications
You must be signed in to change notification settings - Fork 6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
1137. N-th Tribonacci Number #220
1137. N-th Tribonacci Number #220
Comments
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. |
…s 1241175426 Co-authored-by: kovatz <[email protected]> Co-authored-by: topugit <[email protected]> Co-authored-by: basharul-siddike <[email protected]> Co-authored-by: hafijul233 <[email protected]>
…s 1241175426 Co-authored-by: kovatz <[email protected]> Co-authored-by: topugit <[email protected]> Co-authored-by: basharul-siddike <[email protected]> Co-authored-by: hafijul233 <[email protected]>
Discussed in #219
Originally posted by mah-shamim August 2, 2024
Topics:
Math
,Dynamic Programming
,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:
Constraints:
0 <= n <= 37
answer <= 231 - 1
.Hint:
The text was updated successfully, but these errors were encountered: