目录
题目
- 泰波那契序列 Tn 定义如下:
T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2
给你整数 n,请返回第 n 个泰波那契数 Tn 的值。
示例 1:
输入:n = 4
输出:4
解释:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
示例 2:
输入:n = 25
输出:1389537
法一、递归
class Solution:
def tribonacci(self, n: int) -> int:
if n == 0:
return 0
if n <= 2:
return 1
return self.tribonacci(n-1) + self.tribonacci(n-2) + self.tribonacci(n-3)
法二、迭代1
class Solution:
def tribonacci(self, n: int) -> int:
if n == 0:
return 0
if n <= 2:
return 1
a,b,c=0,1,1
d=0
for i in range(3,n+1):
d=a+b+c
a,b,c=b,c,d
return d
法三、迭代2
class Solution:
def tribonacci(self, n: int) -> int:
if n==0:
return 0
elif n==1:
return 1
elif n==2:
return 1
t=[0,1,1]
for i in range(3,n+1):
t.append(t[i-3]+t[i-2]+t[i-1])
return t[n]
标签:契数,return,迭代,int,self,个泰波,1137,tribonacci,Tn
From: https://www.cnblogs.com/lushuang55/p/18125767