70. Climbing Stairs

2017-10-16  本文已影响0人  Al73r

题目

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.

分析

使用dp来做。dp[i]表示台阶i处走到顶端所能使用的方法。那么dp[i]可以分为两种情况:

实现

class Solution {
public:
    int climbStairs(int n) {
        if(n==1) return 1;
        int dp[n];
        dp[n-1] = 1;
        dp[n-2] = 2;
        for(int i=n-3; i>=0; i--){
            dp[i] = dp[i+1] + dp[i+2];
        }
        return dp[0];
    }
};

思考

上一篇下一篇

猜你喜欢

热点阅读