泰波那契序列 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
提示:
0 <= n <= 37
答案保证是一个 32 位整数,即 answer <= 2^31 - 1。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/n-th-tribonacci-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
自己解答
class Solution:
def tribonacci(self, n: int) -> int:
if n ==0:
return 0
list1=[0,1,1]
def calculation(list1,n):
length=len(list1)
if n>=length:
list1.append(list1[length-1] + list1[length-2] + list1[length-3])
calculation(list1,n)
calculation(list1,n)
# print('list1 == :' , list1)
# print('list1[-1] == :' , list1[-1])
return list1[-1]
执行用时:36 ms, 在所有 Python3 提交中击败了79.21% 的用户
内存消耗:14.7 MB, 在所有 Python3 提交中击败了5.31% 的用户
大神解答
class Solution:
def tribonacci(self, n: int) -> int:
# if 0 == n:
# return 0
# elif 1 == n or 2 ==n :
# return 1
list_tn = [0, 1, 1]
def func_tn(list_tn, n):
if n >= len(list_tn):
list_tn.append(func_tn(list_tn, n-1)+func_tn(list_tn, n-2)+func_tn(list_tn, n-3))
return list_tn[n]
return func_tn(list_tn, n)
执行用时:36 ms, 在所有 Python3 提交中击败了79.21% 的用户
内存消耗:14.7 MB, 在所有 Python3 提交中击败了5.31% 的用户
和之前做的斐波那契数列差不多,简单。