
class Solution(object):
def tribonacci(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1 or n == 0:
return n
if n == 2:
return 1
dp_1 = 1
dp_2 = 1
dp_3 = 0
for i in range(3, n + 1):
res = dp_1 + dp_2 + dp_3
dp_3 = dp_2
dp_2 = dp_1
dp_1 = res
i = i + 1
return dp_1
if __name__ == '__main__':
n = 25
Sol = Solution()
res = Solution.tribonacci(Sol, n)
print(res)
本文介绍了一种使用Python实现的斐波那契数列算法,通过递归和动态规划两种方式,重点展示了如何通过迭代优化计算效率。通过实例代码演示了如何计算第25项,并解释了在解决此类问题时的思路和技巧。
353

被折叠的 条评论
为什么被折叠?



