Leetcode Algorithm 070. Climbing Stairs

Leetcode Algorithm 070. Climbing Stairs

Climbing Stairs
有一条n级的楼梯,每次只能走一级或两级,求总共有多少级走法

解题思路

f[i]表示走到第i级的时候的走法,那么我们只可能从第i-1级走一步或者从i-2级走两步到达第i级,故有一条状态转移方程式:
f[i] = f[i-1] + f[i-2]

边界情况有:f[0] = 0; f[1] = 1; f[2] = 2;

可以发现这条状态转移方程类似斐波那契数列,可以用递归法或者迭代法来求解。下面给出迭代法的解法。

代码

#include<iostream>

using namespace std;

class Solution {
public:
    int climbStairs(int n) {
        int f1 = 1;
        int f2 = 2;

        if (n == 0)
            return 0;
        else if (n == 1)
            return f1;
        else if (n == 2)
            return f2;
        else {
            int fn;
            while (n > 2) {
                fn = f1 + f2;
                f1 = f2;
                f2 = fn;
                n--;
            }
            return fn;
        }
    }
};

测试样例

int main() {
    Solution s;

    cout << s.climbStairs(3) << endl;
    cout << s.climbStairs(44) << endl;

    return 0;
}

输出

3
1134903170
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值