话不多说,直接上代码
public static void main(String[] args) {
System.out.println("跳几级台阶:");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println("跳"+n+"级台阶有"+fib(n)+"种方法");
System.out.println("跳"+n+"级台阶有"+fib2(n)+"种方法");
}
//递归(非高效方法)
public static int fib(int n){
if(n<3){
return n;
}
else{
return fib(n-1)+fib(n-2);
}
}
//非递归
public static int fib2(int n){
if(n<3){
return n;
}
else{
int first=1;
int second=2;
int total=0;
while(n-->2){
total=first+second;
first=second;
second=total;
}
return total;
}
}