【LeetCode 70】Climbing Stairs(Python)

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?
题目分析:上楼梯问题,每次可上1或2个台阶,求出达到给定的层数有多少种方法。
示例:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

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

注意:这道题不能用递归,会提示超时,所以需要想一个其他办法。

方法一:

  1. 思路:
    (1)如果起始跳一阶的话,剩余的n-1阶就有 f(n-1) 种跳法;
    (2)如果起始跳二阶的话,剩余的n-2阶就有 f(n-2) 种跳法;
    所以f(n) = f(n-1) + f(n-2),实际结果即为斐波纳契数。
    斐波那契数列:n=1–>1n=2–>2 ;n=3–>n=1的结果+n=2的结果;n=4–>n=2的结果+n=3的结果;n=5–>n=3的结果+n=4的结果… …
    ↓↓↓递归的写法
def test(num):
    if num==1:
        return 1
    elif num==2:
        return 2
    else:
        return test(num-1)+test(num-2)
num = int(input())
print(test(num))

该题应采用递归的逆向思维,从底层向上算。观察斐波那契数列得出的规律。

class Solution:
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        p,q=1,2
        if n<3:
            return n
        else:
            for i in range(n-2):
                p,q=q,p+q
            return q

另外再给大家看一下我第一次写出来的东西(得出的是过程,这个与题意不符):

x=4
for n in range(10):
    for m in range(20):
        if n*1+m*2==x:
            if n>=1 and m>=1:
                print('%d个一和%d个二'%(n,m)) 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值