一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法?
private static HashMap<Integer, Long> record = new HashMap<>();
/**
* 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法
*/
/**
* 分析:
* 当n=1时,只有1种跳法(1);
* 当n=2时,有2种跳法(11,2);
* 当n=3时,有3种跳法(111,12,21)
* 当n=4时,有5种跳法(1111,112,121,211,22)
* 当n=5时,有8种跳法(11111,1112,1121,1211,2111,221,122,212)
* ...
* (n-1)的结果 + (n-2)的结果
* f(n) = f(n-1) + f(n - 2)
*/
public static long jumpMethod1(int step) {
// step=50, num = 20365011074 38927毫秒
if (step <= 0) {
return 0;
}
if (step < 3) {
return step;
} else {
return jumpMethod1(step - 1) + jumpMethod1(step - 2);
}
}
/**
* 空间换时间(把计算过的结果保存起来,每次先查下计算过没有,节省很多时间)
* @param step
* @return
*/
public static long jumpMethod2(int step) {
// 仅用时3毫秒
if (record.containsKey(step)) {
return record.get(step);
}
if (step <= 0) {
return 0;
}
if (step < 3) {
return step;
} else {
long num = jumpMethod2(step - 1) + jumpMethod2(step - 2);
record.put(step, num);
return num;
}
}
/**
* 斐波那契数列
* @param step
* @return
*/
public static long jumpMethod3(int step) {
// 平均耗时 <1毫秒
if (step <= 0) {
return 0;
} else if (step < 3) {
return step;
} else {
long f1 = 0;
long f2 = 1;
long sum = 0;
for (int i = 1; i <= step ; i++) {
sum = f1 + f2;
f1 = f2;
f2 = sum;
}
return sum;
}
}
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。 求该青蛙跳上一个n级的台阶总共有多少种跳法?
/**
* 解析
* 假如有1个台阶, 有1种可能
* 假如有2个台阶, 有2种可能
* 假如有3个台阶, 有3种可能
* ...
* 假如有n个台阶,
* f(n) = f(n - 1) + f(n - 2) + f(n - 3) + ... + f(1)
*/
public static long pro2_jump1(int n) {
if (n <= 0) {
return 0;
} else if (n < 3) {
return n;
} else {
if (record.containsKey(n)) {
return record.get(n);
}
long sum = 0;
for (int i = 1; i <= n ; i++) {
sum += pro2_jump1(n - i);
}
record.put(n, sum);
return sum;
}
}
测试
public static void main(String[] args) {
long jump4 = jumpMethod1(4);
System.out.println(jump4);
long jump5 = jumpMethod1(5);
System.out.println(jump5);
long start = System.currentTimeMillis();
long jump50 = jumpMethod3(50);
long end = System.currentTimeMillis();
System.out.println("jump50="+jump50+","+(end-start)+"毫秒");
long pro2Jump5 = pro2_jump1(5);
System.out.println(pro2Jump5);
}