LeetCode 70. 爬楼梯 Climbing Stairs

简介: LeetCode 70. 爬楼梯 Climbing Stairs

LeetCode 70. 爬楼梯 Climbing Stairs


Table of Contents

一、中文版

二、英文版

三、My answer

四、解题报告


一、中文版

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注意:给定 n 是一个正整数。

示例 1:

输入: 2

输出: 2

解释: 有两种方法可以爬到楼顶。

1.  1 阶 + 1 阶

2.  2 阶

示例 2:

输入: 3

输出: 3

解释: 有三种方法可以爬到楼顶。

1.  1 阶 + 1 阶 + 1 阶

2.  1 阶 + 2 阶

3.  2 阶 + 1 阶

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/climbing-stairs

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、英文版

You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 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


三、My answer

class Solution:
    def climbStairs(self, n: int) -> int:
        #  version 1:
        if n < 1:
            return 0
        if n == 1:
            return 1
        if n == 2:
            return 2
        a = 1
        b = 2
        temp = 0
        for i in range(3,n + 1):
            temp = a + b
            a = b
            b = temp
        return temp
        #     version 2:
        if n == 1:
            return 1
        dp = [0] * (n + 1)
        dp[1] = 1
        dp[2] = 2
        for i in range(3,n+1):
            dp[i] = dp[i-1] + dp[i-2]
        return dp[n]


四、解题报告

数据结构:无

实现:动态规划

算法:动态规划四要素

1.动规的状态 State —— 递归的定义

2.动规的方程 Function —— 递归的拆解

3.动规的初始化 Initialize —— 递归的出口

4.动规的答案 Answer —— 递归的调用

本解法中 version 2 是更规范的动规写法,使用 数组 dp 来存过程状态。而 version 1 只保存变量。

相关文章
LeetCode 70. Climbing Stairs
你正在爬楼梯。 它需要n步才能达到顶峰。 每次你可以爬1或2步。 您可以通过多少不同的方式登顶? 注意:给定n将是一个正整数。
40 0
LeetCode 70. Climbing Stairs
|
算法 移动开发
[LeetCode]--70. Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 这是一个很经典的爬楼梯问题,面试也会经常遇
1129 0
LeetCode 70 Climbing Stairs(爬楼梯)(动态规划)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50514606 翻译 你正在爬一个楼梯。
911 0
|
C++ Python
[LeetCode] Climbing Stairs
Note: If you feel unwilling to read the long codes, just take the idea with you. The codes are unnecessarily long due to the inconvenient handle of matrices.
686 0
|
算法 Python
leetcode 70 Climbing Stairs
 Climbing Stairs                       You are climbing a stair case. It takes n steps to reach to the top.
1099 0
|
机器学习/深度学习
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
2月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
2月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3

热门文章

最新文章