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?

Note: Given n will be a positive integer.

思路:这题其实用排列组合的方法也可以解,但这提的本质其实就是菲波那切数列,r[i+2]其实是由r[i+1]和r[i]分别走一步和两部构成的,所以r[i+2] = r[i+1]+r[i],这样的话解法就很多了。

C++:这是我最开始的解法,但是时间超了。。。:

class Solution {
public:
    void recur(int cur, int n, int &result){
        if (cur > n)
            return;
        else if (cur == n){
            result += 1;
            return;
        }
        else{
            recur(cur + 1, n, result);
            recur(cur + 2, n, result);
        }
    }
    int climbStairs(int n) {
        int result = 0;
        recur(0, n, result);
        return result;
    }
};

Python:当然,可以不用设置数组,直接用常数空间求解:

def climbStairs(self, n):
    a = b = 1
    for _ in range(n):
        a, b = b, a + b
    return a
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值