Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bc097f1

Browse files
N-th Tribonacci Number
1 parent 5394f24 commit bc097f1

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed

‎1137-n-th-tribonacci-number.py

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,33 @@
2323
"""
2424
class Solution:
2525
def tribonacci(self, n: int) -> int:
26-
if n ==0:
27-
return 0
28-
elif n == 1orn==2:
26+
if n <=1:
27+
return n
28+
elif n == 2:
2929
return 1
30-
a = 0
31-
b = c = 1
32-
for i in range(2,n):
33-
ans = a+b+c
34-
a,b,c = b,c,ans
35-
return ans
30+
31+
first, second, third = 0, 1, 1
32+
for _ in range(3, n+1):
33+
first, second, third = second, third, first + second + third
34+
35+
return third
36+
37+
38+
class Solution1:
39+
def tribonacci(self, n: int) -> int:
40+
return self.helper(n, {0:0, 1:1, 2:1})
41+
42+
def helper(self, n, memo):
43+
if n not in memo:
44+
memo[n] = self.helper(n-1, memo) + self.helper(n-2, memo) + self.helper(n-3, memo)
45+
return memo[n]
46+
47+
48+
# TLE
49+
class Solution2:
50+
def tribonacci(self, n: int) -> int:
51+
if n <= 1:
52+
return n
53+
elif n == 2:
54+
return 1
55+
return self.tribonacci(n-1) + self.tribonacci(n-2) + self.tribonacci(n-3)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /