LeetCode70. 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?
分析:若n=1,1种;n=2,2种;n=3,3种;n=4,5种;n=5,8种......即有n阶楼梯时,爬楼梯的方法数有(n-1阶所含方法数 + n-2阶所含方法数)。记得分配指针内存及释放内存,否则会The Time Limit.

class Solution {
public:
    int climbStairs(int n) {
        if(n<=3) return n;
        int *res = new int[n];
        res[0]=1;
        res[1]=2;
        res[2]=3;
        for(int i=3;i<n;i++){
            res[i] = res[i-1]+res[i-2];
        }
        int sum = res[n-1];
        delete res;//释放内存
        return sum;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容