假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? 解决方案 方法一:暴力法 算法 在暴力法中,我们将会把所有可能爬的阶数进行组合,也就是 1 和 2 。而在每一步中我们都会继续调用 climbStairsclimbStairs 这个函数模拟爬 11 阶和22 阶的情...
代码(Python3) class Solution: def climbStairs(self, n: int) -> int: # dp[i] 表示上到第 i 级楼梯的方法数 dp: List[int] = [0] * (n + 1) # 最开始在第 0 级和第 1 级各有一种方案 dp[0], dp[1] = 1, 1 for i in range(2, n + 1): #第 i 级可以从第 i - 1 级...
classSolution:defclimbStairs(self, n:int) ->int: a, b =0,1;foriinrange(n): a, b = b, a+breturnb Python版(通项公式法) class Solution: def climbStairs(self, n: int) -> int: sqrt5 =math.sqrt(5)returnround((pow((1+sqrt5)/2, n+1) -pow((1-sqrt5)/2, n+1)) / sqr...
https://leetcode.com/problems/climbing-stairs/ 题意分析: 爬楼梯,一次可以爬一步或者两步。如果要爬n层,问一共有多少种爬法。比如说,如果是3层,可以有[[1,1,1],[1,2],[2,1]]共3种方法。 题目思路: 这是一个典型的动态规划问题。n层的方法数 = n - 1层的方法数 + n - 2层的方法数。 ...
来自专栏 · 刻意练习之LeetCode 70. Climbing Stairs 问题描述 爬台阶,n个台阶达到山顶:每次只能前进1步或2步。 问:共计有多少种不同的方法,可以攀登到山顶? 测试样例 输入:2,输出:2。解释:1)1step+1step;2)2steps,共计2种方式; 输入:3,输出:3。解释:1)1step+1step+1step;2)...
LeetCode 70. Climbing Stairs 简介:你正在爬楼梯。 它需要n步才能达到顶峰。每次你可以爬1或2步。 您可以通过多少不同的方式登顶?注意:给定n将是一个正整数。 Description You are climbing a stair case. It takes n steps to reach to the top....
leetcoe 斐波那契初探 70. Climbing Stairs 这个经典了, 我记得以前看过清华版数据结构第一章, 整章都是讲这个的。 写的非常不错, 可惜没有PYTHON版的, 希望什么时候出一版python的哈哈。 《天才基本法》里也有问这个上梯子的桥段。 题目, You are climbing a staircase. It takes n steps to reach the ...
LeetCode Climbing Stairs 1.题目 You are climbing a stair case. It takesnsteps 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? 2.解决方案 classSolution{ public:...
fn = fnm1 + fnm2; fnm2 = fnm1; fnm1 = fn; } return fn; } }; 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 参考 1.leetcode_ClimbingStairs; 2. solution; 完...
Can you solve this real interview question? Climbing 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