递归很消耗内存(欢迎大神讲解下原理),而使用堆栈可以节省内存的开销。
package 斐波那契数列_堆栈法与递归法比较;
import java.util.*;
public class Main {
static int recursion(int n){
if(n==1)
return 1;
if(n==2)
return 1;
else
return recursion(n-1)+recursion(n-2);
}
static int stack(int n){
Stack<Integer> stack=new Stack<Integer>();
stack.push(new Integer(1));
stack.push(new Integer(1));
int k=3;
while(k<=n){
//for(int i=1;i<=2;i++){
Integer F1=stack.pop();
int f1=F1.intValue();
Integer F2=stack.pop();
int f2=F2.intValue();
Integer t=new Integer(f1+f2);
stack.push(t);
stack.push(F2);
k++;
//}
}
stack.pop();
return stack.pop();
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
in.close();
long time;
long st;
long et;
long value;
st=System.currentTimeMillis();
value=recursion(n);
et=System.currentTimeMillis();
System.out.println("斐波那契数列递归法"+value+" 耗时"+(et-st));
st=System.currentTimeMillis();
value=stack(n);
et=System.currentTimeMillis();
System.out.println("斐波那契数列堆栈法"+value+" 耗时"+(et-st));
}
}
//40
//斐波那契数列递归法102334155 耗时369
//斐波那契数列堆栈法102334155 耗时0