变态跳台阶(剑指offer_10.4)

题目描述


一只青蛙一次可以跳上1级台阶,也可以跳上2级...它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

解题思路


动态规划

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];
}

数学推导

跳上n-1级台阶,可以从n-2级跳1级上去,也可以从n-3级跳两级上去...,那么

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

同样,跳上n级台阶,可以从n-1级跳1级上去,也可以从n-2级跳2级上去...,那么

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

综上可得

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

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

所以f(n)是一个等比数列

public int JumpFloorII(int target) {
    return (int) Math.pow(2, target - 1);
}
原文地址:https://www.cnblogs.com/ziytong/p/12096708.html