Problem

A child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs.

Example

n=3
1+1+1=2+1=1+2=3=3

return 4

Solution

public class Solution {
    /*
     * @param n: An integer
     * @return: An integer
     */
    public int climbStairs2(int n) {
        // write your code here
        int[] dp = new int[n+3];
        dp[0] = 1;
        dp[1] = 1;
        dp[2] = 2;
        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i-1] + dp[i-2] + dp[i-3];
        }
        return dp[n];
    }
};

linspiration
161 声望53 粉丝