问题描述
- 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法
- 地址:牛客链接
解决方法:
- 用f(n)表示要跳到第n级台阶的跳法,那么如果要跳到第n级台阶,可以从第n-1级台阶跳11级到第n级,也可以从第n-2级台阶跳2级到第n级。所以 f(n) = f(n-2) + f(n-1)
- 根据规律可以发现,这类似于斐波那契数列,初始条件 f(0) = 0,f(1) = 1,f(2) = 2
- 所以,可以用求解斐波那契数列的方法来解决该题,具体详解见另一篇博客:剑指offer-斐波那契数列
经验教训
- 根据题意找依赖关系
代码实现
public int JumpFloor(int target) {
if(target <= 2) {
return target;
}
int preValue = 1;
int curValue = 2;
for(int i = 3; i <= target; i++){
curValue = preValue + curValue;
preValue = curValue - preValue;
}
return curValue;
}