CS-Notes/notes/10.4 变态跳台阶.md
2021-03-23 02:48:19 +08:00

61 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 10.4 变态跳台阶
## 题目链接
[牛客网](https://www.nowcoder.com/practice/22243d016f6b47f2a6928b4313c85387?tpId=13&tqId=11162&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 题目描述
一只青蛙一次可以跳上 1 级台阶也可以跳上 2 ... 它也可以跳上 n 求该青蛙跳上一个 n 级的台阶总共有多少种跳法
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/cd411a94-3786-4c94-9e08-f28320e010d5.png" width="380px"> </div><br>
## 解题思路
### 动态规划
```java
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 级跳 2 级上去...那么
```
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) 是一个等比数列
```source-java
public int JumpFloorII(int target) {
return (int) Math.pow(2, target - 1);
}
```