Skip to content

Commit 37a9e68

Browse files
committed
Create 2024-05-01-Leetcode-1137.md
1 parent e191a33 commit 37a9e68

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
---
2+
title: Leetcode 1137. N-th Tribonacci Number
3+
description: Explanation for Leetcode 1137 - N-th Tribonacci Number, and its solution in Python.
4+
date: 2025-05-01
5+
categories: [Leetcode, Dynamic Programming, Easy]
6+
tags: [Leetcode, Python, Study, Dynamic Programming, Easy]
7+
math: true
8+
---
9+
10+
## Problem
11+
[Leetcode 1137 - N-th Tribonacci Number](https://leetcode.com/problems/n-th-tribonacci-number/description/)
12+
13+
Example:
14+
```
15+
Input: n = 4
16+
Output: 4
17+
Explanation:
18+
T_3 = 0 + 1 + 1 = 2
19+
T_4 = 1 + 1 + 2 = 4
20+
21+
Input: n = 25
22+
Output: 1389537
23+
```
24+
25+
## Approach
26+
27+
Using array, we can store the all previous values. For example, we can save T_0, T_1, T_2. With the information, we can calculate T_3, T_4, and up to T_n in the saved array.
28+
29+
Thus we can return T_n at the end
30+
31+
Here is the Python code for the solution:
32+
```python
33+
class Solution:
34+
def tribonacci(self, n: int) -> int:
35+
dp = [0, 1, 1]
36+
37+
if n < 3:
38+
return dp[n]
39+
40+
for i in range(3, n+1):
41+
total = dp[i-1] + dp[i-2] + dp[i-3]
42+
dp.append(total)
43+
44+
return dp[-1]
45+
```
46+
## Time Complexity and Space Complexity
47+
48+
Time Complexity: $O(n)$
49+
50+
Space Complexity: $O(n)$

0 commit comments

Comments
 (0)