LeetCode 70. 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?

 

一开始想用排列组合的方式,但是公式不太好些,后来想用递归的方式,最后剩一个台阶1种,最后剩2个台阶两种,然后那个台阶相当于n-1个台阶的方法总数加上n-2个台阶的方法总数,但是这样会超时。

最后用循环代替递归,台阶数不要倒着来,一个台阶一种,二个台阶2种,三个台阶种类数时一个台阶种类数加两个台阶种类数以此类推。

class Solution {
public:
    int climbStairs(int n) {//最后一步可以是一阶或者两阶,上一个台阶只有一种走法,两个台阶两种走法,递归会超时
     vector<int> waysOfNSteps(n);
     if(n == 1){
         return 1;
     }
     else if(n == 2){
         return 2;
     }
     else{
         
         waysOfNSteps[0] = 1;
         waysOfNSteps[1] = 2;
         for(int i = 2 ;i<n;i++ ){
             waysOfNSteps[i] = waysOfNSteps[i-1]+waysOfNSteps[i-2];
         }
     }
     return waysOfNSteps[n-1];
        
    }
};

 

posted @ 2016-09-06 22:49  熊阳  阅读(99)  评论(0编辑  收藏  举报