Date and Time: Aug 22, 2024, 17:20 (EST)
Link: https://leetcode.com/problems/n-th-tribonacci-number/
The Tribonacci sequence
Given n
, return the value of
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
-
0 <= n <= 37
-
The answer is guaranteed to fit within a 32-bit integer, ie.
answer <= 2^31 - 1
.
Similar to fibonacci number, we first store the base case dp = [0, 1, 1]
, then we repeatly append dp
with dp[i-1] + dp[i-2] + dp[i-3]
for range(3, n+1)
. And we return dp[n]
.
class Solution:
def tribonacci(self, n: int) -> int:
dp = [0, 1, 1]
if n < 3:
return dp[n]
for i in range(3, n+1):
dp.append(dp[i-3] + dp[i-2] + dp[i-1])
return dp[n]
Time Complexity:
Space Complexity: