Monday, May 6, 2013

Leetcode: Climbing Stairs in C++



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:
int climb(int n, vector<int>& ways)
    {
        if(n<0)
        return 0;
        if(ways[n]==-1)
        {
            ways[n] = climb(n-1, ways)+climb(n-2, ways);
            return ways[n];
        }
        else
            return ways[n];
    }
    int climbStairs(int n) {
        if(n==0)
        return 1;
        if(n<0)
        return 0;
        vector<int> ways(n+1,-1);
        ways[0]=1;
        return climb(n, ways);
    }

No comments:

Post a Comment