一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
解答:1,2,3,4阶对应的跳法种数分别为1,2,4,8
递归法:
跳1级,剩下n-1级,则剩下跳法是f(n-1)
跳2级,剩下n-2级,则剩下跳法是f(n-2)
所以f(n)=f(n-1)+f(n-2)+…+f(1)
因为f(n-1)=f(n-2)+f(n-3)+…+f(1)
所以f(n)=2*f(n-1)
非递归法:
由规律可知是2的i次方
如果target数值过大,比如50,递归结果就为0了,栈溢出。
public class o_9 {
//递归
public int jump(int target) {
if (target <= 1)
return target;
else {
return jump(target - 1) * 2;
}
}
//非递归
public int jump2(int target) {
int sum = (int) Math.pow(2, target - 1);
return sum;
}
public static void main(String[] args) {
o_9 o9 = new o_9();
int target = 5;
int result = o9.jump(target);
int result2 = o9.jump2(target);
System.out.println(result);
System.out.println(result2);
}
}