【leetcode】70. Climbing Stairs 每次一阶或两阶爬楼梯

1. 题目

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?

爬N阶的楼梯,每次可以爬1阶或者2阶,一共有多少种爬法?

2. 思路

i阶有cs[i]种,则:
cs[n] = cs[n-1] + cs[n-2]

解释:以n-2阶结束,一次两阶;以n-1阶结束,一次一阶。

3. 代码

class Solution {
public:
    // cs[n] = cs[n-1] + cs[n-2]
    // cs[0] = 1; cs[1] = 1; cs[2] = 2;
    int climbStairs(int n) {
        int cs[n+1];
        cs[0] = cs[1] = 1; cs[2] = 2;
        for (int i = 3; i < n+1; i++) {
            cs[i] = cs[i-1] + cs[i-2];
        }
        return cs[n];
    }
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007400839
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞