当前位置:网站首页>LeetCode之三步问题
LeetCode之三步问题
2022-06-28 07:48:00 【little亮_】
题目
三步问题。有个小孩正在上楼梯,楼梯有n阶台阶,小孩一次可以上1阶、2阶或3阶。实现一种方法,计算小孩有多少种上楼梯的方式。结果可能很大,你需要对结果模1000000007。
示例1:
输入:n = 3
输出:4
说明: 有四种走法
示例2:输入:n = 5
输出:13来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/three-steps-problem-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
和青蛙跳台阶一样,首先写出前几步的结果:
通过这些结果,可以发现规律:
f(n)=f(n-1)+f(n-2)+f(n-3) (n≥3,且f(0)=f(1)=1,f(2)=2),有了这个规律之后,代码就很好写啦!也许,有些小伙伴会说,你怎么知道一上来就知道找规律就可以得到正确的结果的?其实我一开始也不知道,就是抱着尝试的态度去的(因为我之前在做“青蛙跳台阶”的时候学到的这个方法,而这个题目和它非常的相似,所以很容易就类比想到这种方法啦!因此,解题的王道:多做,多总结。)
源码
class Solution:
# 类似于只有一次只能爬一阶楼梯或者两阶楼梯,对其进行找规律,发现:f(n)=f(n-1)+f(n-2)+f(n-3) (n≥3,且f(0)=f(1)=1,f(2)=2)
def waysToStep(self, n: int) -> int:
if n == 1: return 1
if n == 2: return 2
n0, n1, n2 = 1, 1, 2
for i in range(n - 2):
n0, n1, n2 = n1, n2, (n0 + n1 + n2) % 1000000007
# print(n2)
return n2通过截图

同步更新于个人博客系统:LeetCode之三步问题
边栏推荐
- Static resource compression reduces bandwidth pressure and increases access speed
- Cloud native (to be updated)
- Recommended system series (Lecture 5): Optimization Practice of sorting model
- kubelet驱逐机制的源码分析
- kubernetes删除pod的流程的源码简析
- Software design of power control board
- linux下修改mysql用户名root
- 逆波兰表达式求值<难度系数>
- Spark 离线开发框架设计与实现
- No suspense about the No. 1 Internet company overtime table
猜你喜欢
随机推荐
打新债注册开户靠谱吗?安全吗?
How to insert a single quotation mark into a table as a data type in Oracle pl/sql
Installing redis on Linux
NDK cross compilation
券商注册开户靠谱吗?安全吗?
Ice - resources
es6箭头函数中return的用法
自动化测试的生命周期是什么?
Install haproxy
Spark 离线开发框架设计与实现
Section VI UART of zynq
8 张图 | 剖析 Eureka 的首次同步注册表
HJ explicit random number
Soft exam -- software designer -- afternoon question data flow diagram DFD
Tencent continued to lay off staff in the second half of the year, and all business groups reduced by at least 10%. What do you think of this? Followers
分析 NFT 项目的 5 个指标
Open62541 import nodeset file directly
Recommended system series (Lecture 5): Optimization Practice of sorting model
DBeaver 22.1.1 发布,可视化数据库管理平台
扩展Prometheus的解决方案thanos的简介和几个月使用心得










