题目描述
泰波那契序列 Tn 定义如下:
T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2
给你整数 n,请返回第 n 个泰波那契数 Tn 的值。
题解 python3
class Solution:
def tribonacci(self, n: int) -> int:
# 空间复杂度 O(n)
# res = [0,1,1]
# for i in range(2, n):
# res.append(res[i] + res[i-1] + res[i-2])
# return res[n]
# 空间复杂度O(1)
if n==0: return 0
if n==1 or n==2: return 1
n1 = 0
n2 = 1
n3 = 1
for i in range(0, n-2):
n1, n2, n3 = n2, n3, n1+n2+n3
return n3