Abnormal jump stairs (to prove safety offer_10.4)

Title Description


A frog can jump on a Class 1 level, you can also hop on level 2 ... n it can also jump on stage. The frog jumped seeking a total of n grade level how many jumps.

Problem-solving ideas


Dynamic Programming

public int JumpFloorII(int target)
{
    int[] dp = new int[target];
    Arrays.fill(dp,1);
    for(int i =1;i<target;i++)
        for(int j =0;j<i;j++)
            dp[i] += dp[j];
    return dp[target-1];
}

Mathematical derivation

Jump stairs n-1, n-2 can jump from level 1 up stage, may jump up from the two-stage n-3 ..., then

f(n-1) = f(n-2) + f(n-3) + ...+ f(0)

Also, jump n steps, can jump up from level 1 level n-1, stage 2 may jump from the n-2 ... up stage, then

f(n) = f(n-1) + f(n-2) + ... +f(0)

In summary available

f(n) - f(n-1) = f(n-1)

which is

f(n) = 2*f(n-1)

Therefore, f (n) is a geometric sequence

public int JumpFloorII(int target) {
    return (int) Math.pow(2, target - 1);
}

Guess you like

Origin www.cnblogs.com/ziytong/p/12096708.html