-
Notifications
You must be signed in to change notification settings - Fork 13
/
1137-n-th-tribonacci-number.py
55 lines (43 loc) · 1.27 KB
/
1137-n-th-tribonacci-number.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
Problem Link: https://leetcode.com/problems/n-th-tribonacci-number/
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
"""
class Solution:
def tribonacci(self, n: int) -> int:
if n <= 1:
return n
elif n == 2:
return 1
first, second, third = 0, 1, 1
for _ in range(3, n+1):
first, second, third = second, third, first + second + third
return third
class Solution1:
def tribonacci(self, n: int) -> int:
return self.helper(n, {0:0, 1:1, 2:1})
def helper(self, n, memo):
if n not in memo:
memo[n] = self.helper(n-1, memo) + self.helper(n-2, memo) + self.helper(n-3, memo)
return memo[n]
# TLE
class Solution2:
def tribonacci(self, n: int) -> int:
if n <= 1:
return n
elif n == 2:
return 1
return self.tribonacci(n-1) + self.tribonacci(n-2) + self.tribonacci(n-3)