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?

疯狂收割easy题。。。这题是DP,递推式是dp[i] = dp[i-1] + dp[i-2],也就是斐波拉切数列。
为什么?可以这样想:爬到i-1格再跨1步就能到i,爬到i-2格再跨2格就能到i。

覃超还提出了如果能走1/2/3步,或者走了一步之后下一步距离不能跟前一步相同的情况。

    public int climbStairs(int n) {
        if (n == 1) return 1;
        if (n == 2) return 2;
        int[] dp = new int[n+1];
        dp[1] = 1;
        dp[2] = 2;
        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }

你可能感兴趣的:(70. Climbing Stairs)