1. 本题知识点
递归
2. 题目描述
一只青蛙一次可以跳上 1 级台阶,也可以跳上 2 级。求该青蛙跳上一个 n 级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
3. 解决思路
- 当 n = 1 时,有 1 种跳法
- 当 n = 2 时,有 2 种跳法
- 当 n = 3 时,有 3 种跳法
- 跳 n 阶台阶,可以先跳 1 阶台阶,再跳 n-1 阶台阶;或者先跳 2 阶台阶,再跳 n-2 阶台阶。
于是可以得到以下递推公式
f
(
n
)
=
{
1
,
n = 1
2
,
n = 2
f
(
n
−
1
)
+
f
(
n
−
2
)
,
n > 2
f(n) = \begin{cases} 1, & \text{n = 1} \\ 2, & \text{n = 2} \\ f(n-1) + f(n-2),& \text{n > 2} \end{cases}
f(n)=⎩⎪⎨⎪⎧1,2,f(n−1)+f(n−2),n = 1n = 2n > 2
4. 代码
使用递归
public class Solution {
public int JumpFloor(int target) {
if(target < 3) {
return target;
}
return JumpFloor(target-1) + JumpFloor(target -2);
}
}
使用迭代
public class Solution2 {
public int JumpFloor(int target) {
if(target < 3) {
return target;
}
int pre1 = 1;
int pre2 = 2;
int result = 0;
for (int i = 3; i <= target; i++) {
result = pre1 + pre2;
pre1 = pre2;
pre2 = result;
}
return result;
}
}