package cn.itcast.offer1;
/*
* 一只青蛙一次可以跳上1层台阶,也可以跳2层,求该青蛙跳上一个N层的台阶共有多少种跳法
public static void main(String[] args) {
// TODO Auto-generated method stub
int x=method(3);
System.out.println("total="+x);
}
public static int method(int n){
if (n<0){
return -1;
}
else if (n==1){
return 1;
}
else if (n==2){
return 2;
}
else{
return method(n-1)+method(n-2);
}
}
}
/*
* 一只青蛙一次可以跳上1层台阶,也可以跳2层,求该青蛙跳上一个N层的台阶共有多少种跳法
*/
思路分析:
假设青蛙最后一次跳台阶,如果跳1层,则前n-1层有f(n-1)种方法;如果跳2层,则前n-2层有f(n-2)种方法,因此n层台阶共有f(n-1)+f(n-2)=f(n)种跳法;
public class OfferQingwa {public static void main(String[] args) {
// TODO Auto-generated method stub
int x=method(3);
System.out.println("total="+x);
}
public static int method(int n){
if (n<0){
return -1;
}
else if (n==1){
return 1;
}
else if (n==2){
return 2;
}
else{
return method(n-1)+method(n-2);
}
}
}