一、题目
————————————————
一只青蛙一次可以跳上 1 级台阶,也可以跳上 2 级... 它也可以跳上 n 级。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
————————————————
————————————————
二、思路
————————————————
数学推导
跳上 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) = 2*f(n-1)
所以 f(n) 是一个等比数列
————————————————
三、解决问题
————————————————
测试用例
1.功能测试(3,5,8等)
2.边界值测试(0,1,2等)
3.性能测试(50,100等)
4.特殊(0、负数)
————————————————
package swordoffer;
/**
* @author LQ
* @version 1.0
* @date 2020-03-15 20:09
*/
/**
* 一只青蛙一次可以跳上 1 级台阶,也可以跳上 2 级... 它也可以跳上 n 级。
* 求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
*/
public class Solution12 {
public static void main(String[] args) {
Solution12 demo = new Solution12();
System.out.println(demo.JumpFloorII(1));
System.out.println(demo.JumpFloorII(2));
System.out.println(demo.JumpFloorII(8));
System.out.println(demo.JumpFloorII(50));
System.out.println(demo.JumpFloorII(100));
System.out.println(demo.JumpFloorII(0));
}
public int JumpFloorII(int target) {
if(target < 1){
//当target<0,不符合约束条件
throw new RuntimeException("下标错误,应从1开始!");
}
return (int) Math.pow(2, target - 1);
}
}
————————————————
————————————————
努力也是需要学习的,别再让你的努力,只感动了自己!愿你的每一次努力,都能为自己和别人创造价值。

京公网安备 11010502036488号