题目:

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?

 

思路: 此题可以由迭代或DP解决,在此贴一个 top down的DP

 

代码:

 

class Solution {
public:
    
    int helper(int n, vector<int> &map){
        
        if (n < 0) return 0;
        else if (n == 0) return 1;
        else if (map[n-1] > -1) return map[n-1];
        else{
            
            map[n-1] = helper(n-1, map)+helper(n-2, map);
            return map[n-1];
        }
    }
    
    int climbStairs(int n) {
        
        vector<int> map(n,-1);
        return helper(n, map);
    }
};

  

posted on 2013-04-30 07:40  tanghulu321  阅读(156)  评论(0编辑  收藏  举报