本文主要是介绍Leet Code OJ 70. Climbing Stairs [Difficulty: Easy] -python,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
爬楼梯问题:
70. Climbing Stairs
Easy
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?
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
Constraints:
1 <= n <= 45
题意:
你现在在爬楼梯,爬到顶要n阶。每次你可以爬1或2阶楼梯,你有多少种不同的爬法可以到顶?
解题思路:
解法1:观察规律
当n=1时,有1种解法;
当n=2时,有2种解法;
当n=3时,有3种解法;
当n=4时,有5种解法;
当n=5时,有8种解法;
当n=6时,有13种解法;
……
可以看出这是斐波那契数列。问题便迎刃而解。
#70 爬楼梯:斐波那契数列
class Solution:def climbStairs(self, n: int) -> int:pre, cur = 1, 1for i in range(1,n):pre,cur=cur,pre+curreturn cur
解法2:动态规划。
当有n个台阶时,可供选择的走法有两种:
1.首先跨1阶,再跨剩下n-1阶;
2.首先跨2阶,再跨剩下n-2阶。
总数就是两种情况之和。
class Solution(object):def climbStairs(self, n):""":type n: int:rtype: int"""if n == 0 or n == 1 or n == 2:return nsteps = [1, 1]for i in range(2, n+1):steps.append(steps[i-1] + steps[i-2])return steps[n]
这篇关于Leet Code OJ 70. Climbing Stairs [Difficulty: Easy] -python的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!