# leetcode #70 in cpp

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?

Solution:

Code:

class Solution {
public:

int climbStairs(int n) {
vector<int> dp(n+1,0);//dp[i] = distinct ways from i to n
if(n-1 >= 0) dp[n-1] = 1;//position with 1 step from destination. only 1 way to reach the destination
if(n-2 >= 0) dp[n-2] = 2;//position with 2 steps from destination. only 2 way to reach the destination;
for(int i = n-3; i >=0 ; i --){
dp[i] = dp[i+2]+dp[i+1];//distinct ways from position i to n: 1. we take one step to i+1; 2. we take 2 steps to i+2
}                            //thus distinct ways from position i to n is the sum of the ones at i+1 and i+2
return dp[0];

}
};

07-27 2210

03-05 272

08-19 3197

#### LeetCode cpp最新中文题解.pdf

2018年01月10日 866KB 下载

08-05 503

09-21 628

07-17 816

03-20 235

05-08 85

01-14 5074