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?

方法: DP, O(n)

public class Solution {
    public int climbStairs(int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int[] map = new int[n+1];
        for(int i = 0; i <= n; i++)
            map[i] = -1;
        return climbStairs(n, map);
    }
    
    public int climbStairs(int n, int[] map){
        if(n < 0)
            return 0;
        else if(n == 0)
            return 1;
        else if(map[n] > -1)
            return map[n];
        else {
            map[n] = climbStairs(n-1, map) + climbStairs(n-2, map);
            return map[n];
        }
    }
}





你可能感兴趣的:(LeetCode)