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
72 声望28 粉丝

行万里路,读万卷书