Monday, April 6, 2015

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?
Solution1: Dynamic programming
用recursion会time limit exceeded.  用DP可以避免计算重复信息,递推公式:f(n) = f(n-1)+f(n-2)
public class Solution {
    public int climbStairs(int n) {
        if(n == 0)
            return 0;
        if(n < 2) 
            return 1;

        int[] res = new int[n + 1];
        res[0] = 1;
        res[1] = 1;
        for(int i = 2; i <= n; i++) {
            res[i] = res[i - 1] + res[i - 2];
        }
        return res[n];
    }
}
Solution2: 斐波那契数列
public class Solution {
    public int climbStairs(int n) {
        int f1 = 1;
        int f2 = 2;
        if(n == 1)
            return f1;
        if(n == 2)
            return f2;
        
        for(int i = 3; i <= n; i++) {
            int f3 = f1 + f2;
            f1 = f2;
            f2 = f3;
        }
        
        return f2;
    }
}

No comments:

Post a Comment