首页 > 其他分享 >Climbing Stairs

Climbing Stairs

时间:2023-06-19 12:12:39浏览次数:48  
标签:ways 阶有 top step steps Climbing climb Stairs

You are climbing a staircase. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Example 1:

Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

Solution:

class Solution:
    # 通过列举可知,1阶有1种方法,2阶有2种方法,3阶有3种方法,
    # 4阶有5种方法,其符合斐波那契数列,n阶=n-1阶+n-2阶,
    # 于是可用列表s[n]记入n阶有的方法数,并通过s.append()进行记入。
    def climbStairs(self, n: int) -> int:
        s=[1,2]
        if n<=2: # 若为一步就数组第一个值,若为两步就第二个值
            return s[n-1]
        while len(s)<n:
            s.append(s[-1]+s[-2])
        return s[-1]

标签:ways,阶有,top,step,steps,Climbing,climb,Stairs
From: https://www.cnblogs.com/artwalker/p/17490828.html

相关文章

  • leetcode 746. Min Cost Climbing Stairs
    Onastaircase,thei-thstephassomenon-negativecostcost[i]assigned(0indexed).Onceyoupaythecost,youcaneitherclimboneortwosteps.Youneedtofindminimumcosttoreachthetopofthefloor,andyoucaneitherstartfromthestepwithin......
  • 746. Min Cost Climbing Stairs刷题笔记
    题目描述出bug的时候输出打印dp就行classSolution:defminCostClimbingStairs(self,cost:List[int])->int:n=len(cost)+1ifn<=3:returnmin(cost[0],cost[1])dp=[0]*ncost.append(0)foriinrange(2......
  • 70. Climbing Stairs刷题笔记
    问题描述该题考察的是动态规划classSolution:defclimbStairs(self,n:int)->int:dp=[0]*nifn==1:return1dp[0]=1dp[1]=2foriinrange(2,n):dp[i]=dp[i-1]+dp[i-2]ret......
  • 70. Climbing Stairs
    第一次自己想到用dpclassSolution{public:intdp[100];intclimbStairs(intn){dp[0]=1;dp[1]=1;for(inti=2;i<100;++i)dp[i]=dp[i-1]......
  • HDU 5433 Xiao Ming climbing
    ProblemDescriptionDuetothecursemadebythedevil,XiaoMingisstrandedonamountainandcanhardlyescape.Thismountainisprettystrangethat......
  • CF1553I Stairs 题解
    linkSolution虽然但是,这个sb题目真的很sb,不知道怎么评到3400的,也不知道为什么我又没有做出来......
  • LeetCode 70. Climbing Stairs
    ​​题目​​classSolution{public:intdp[10005];intclimbStairs(intn){dp[1]=1;dp[2]=2;for(inti=3;i<=n;i++)......
  • 746.min-cost-climbing-stairs 使用最小花费爬楼梯
    题目描述746.使用最小花费爬楼梯解题思路相当于爬楼梯的进阶版,递推关系变复杂了一些,但本质没有变。\(a_n=min(a_{n-1}+cost[i-1],a_{n-2}+cost[i-2])\)......
  • 70.climbing-stairs 爬楼梯
    题目描述70.爬楼梯解题思路本质上与斐波那契数是一样的:\(a_n=a_{n-1}+a_{n-2}\)构建for循环来遍历。代码classSolution{public:intclimbStairs(i......