赞
踩
泰波那契序列 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。
通过次数146,734提交次数240,480
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/n-th-tribonacci-number
- n = 25
- def result(n):
- if n == 0:
- return 0
- if n == 1:
- return 1
- if n == 2:
- return 1
- return result(n-1) + result(n-2) + result(n-3)
-
- print(result(n))
不是正确答案,原因:
递归太过于暴力
- n = int(input())
- if n == 0:
- print(0)
- if n == 1:
- print(1)
- if n == 2:
- print(1)
- a = 0
- b = 1
- c = 1
- for i in range(3,n+1):
- d = a + b + c
- a = b
- b = c
- c = d
-
- print(c)
- n = int(input())
- ls = [0]*10000000
- ls[0] = 0
- ls[1] = 1
- ls[2] = 1
- for i in range(3,n+1):
- ls[i] = ls[i-1] + ls[i-2] + ls[i-3]
- print(ls[n])
相似题链接
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。