剑指offer——10.4 变态跳台阶

10.4 变态跳台阶

题目链接

NowCoder

题目描述

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


解题思路

动态规划

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int jumpFloorII(int number) {
if(number==0)
return number;
int total=1;
for(int i=1;i<number;i++)
total*=2;
return total;
}
};

数学推导

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

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

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

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

综上可得

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

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

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

f(n) = 2^(n-1) n>=1 =>求和 sn= 2^(n-1)

![image-20220502203248845](算法-剑指offer-10.4 变态跳台阶/image-20220502203248845.png)

1
2
3
public int JumpFloorII(int target) {
return (int) Math.pow(2, target - 1);
}
创作不易,欢迎打赏!
-------------本文结束感谢您的阅读-------------