当前位置:网站首页>LeetCode刷题——泰波那契数列
LeetCode刷题——泰波那契数列
2022-06-29 08:41:00 【书香恋仁心】
泰波那契数列:n=0,T(0)=0 n=1,T(1)=1 n=2,T(2)=1
n>=3时,T(n) =T(n-1)+T(n-2)+T(n-3)
解题思路
n>2时,设了a0,a1,a2=0,1,1
假设n=3,则t_3 = a0+a1+a2 其实也就是前三项和
如何再将a1赋值给a0,a2赋值给a1,前三项和赋值给a2(ao=a1,a1=a2,a2=t_3)
循环次数就是
假设
n=3 n-2=1
n=4 n-2=2
n=5 n-2=3
class Solution:
def tribonacci(self, n):
if n == 0:
return 0
if n <= 2:
return 1
a0, a1, a2 = 0, 1, 1
for i in range(n -2):
num = a0 + a1 + a2
a0 = a1
a1 = a2
a2 = num
return num
n>=3时,本来想用递归解决的,但是超过了python的最大递归深度
递归代码如下
import sys
sys.setrecursionlimit(1000)
class Solution:
def tribo_nacci(self, n):
if n == 0:
return 0
elif n <= 2:
return 1
else:
return self.tribo_nacci(n - 1) + self.tribo_nacci(n - 2) + self.tribo_nacci(n - 3)
s = Solution()但是非常不建议用递归来写,因为他真的非常消耗cpu资源
边栏推荐
- 第十二章 信号(二)- 生产者消费者示例
- Open3d hidden point removal
- 《网络是怎么样连接的》读书笔记 - WEB服务端请求和响应(五)
- Wechat applet project: wechat applet page layout
- LFFD:一种用于边缘检测的轻量化快速人脸检测器
- Twinmotion 初学者教程
- Self cultivation (XXI) servlet life cycle, service method source code analysis, thread safety issues
- SSD改進CFENet
- Wechat applet sub components transfer values to the page (communication between parent and child components) with source code
- What is hyperfusion? What is the difference with traditional architecture
猜你喜欢

pytorch总结学习系列-操作

Wechat applet sharing page, sharing to the circle of friends

Find the most repeated element in the string

Wechat applet wx Navigateback returns the parameters carried on the previous page

Lffd: a lightweight fast face detector for edge detection

Gd32f4xx Ethernet chip (ENC28J60) driver migration

Pytorch Summary - Automatic gradient

Print service IP setting scheme

SPI drive of lsm6dsl

YOLACT实时实例分割
随机推荐
Wechat applet project: wechat applet page layout
How is epoll encapsulated in golang?
Iso16000-9 testing of volatile organic compounds in building products and furniture
Pytorch summary learning series - broadcast mechanism
Laravel 8 enables the order table to be divided by month level
In the era of data processing, data quality construction is the way for enterprises to survive
Factory mode
Go deep into RC, RS, daemonset and statefulset (VII)
Pytorch summary learning series - data manipulation
UE4 animation redirection
通识篇:原型设计的认知,设计及最佳实践
微信小程序项目:tab导航栏
深卷积神经网络时代的目标检测研究进展
How to do unit test well
Written test question "arrange version numbers from large to small"
UE4 在4.20-23版本安裝Datasmith插件
Summary of 3DMAX jamming, white screen and rendering crash
The former security director of Uber faced fraud allegations and concealed the data leakage event
The former security director of Uber faced fraud allegations and had concealed data leakage incidents
Debugging H5 page -weinre and spy debugger real machine debugging