Leetcode - N-th Tribonacci Number (Python)

preview_player
Показать описание
September 2021 Leetcode Challenge
Leetcode - N-th Tribonacci Number #1137
Difficulty: Easy
Рекомендации по теме
Комментарии
Автор

Enjoyed both the O(n) and O(1) space complexity. Here's my solution if you're thinking from left to right from a Fibonacci sequence idea:

0, 1, 1, 2, 3, 5, 8, 13, 21, ...

class Solution(object):
def tribonacci(self, n):
"""
:type n: int
:rtype: int
"""
prev1, prev2, prev3 = 0, 1, 1 #, output
if n == 0:
return prev1
if n == 1:
return prev2
if n == 2:
return prev3

output = 0
for _ in range(3, n + 1):
output = prev1 + prev2 + prev3
prev1 = prev2
prev2 = prev3
prev3 = output
return output

edwardteach
Автор

this solution is so elegant, love it!

ki
Автор

You know nothing John Snow ❄️❄️...Lol, jokes aside...
I always love your video and simple😀 keep up the good work!

chinmaykulkarni
Автор

Hi please can someone explain to me why t[i] = t[i-1] + t[i-2] + t[i-3]

sancho