以Fibonacci数列为例
1,
var s=0;var aa=function(n){
s++;
return n<2?n:aa(n-1)+aa(n-2);
}
for(var i=0;i<=10;i++)
{
document.writeln('result: '+'n='+i+';value='+aa(i)+'<br />');
document.writeln('Function aa running '+s+'<br />');
}
value:
result: n=0;value=0
Function aa running 1
result: n=1;value=1
Function aa running 2
result: n=2;value=1
Function aa running 5
result: n=3;value=2
Function aa running 10
result: n=4;value=3
Function aa running 19
result: n=5;value=5
Function aa running 34
result: n=6;value=8
Function aa running 59
result: n=7;value=13
Function aa running 100
result: n=8;value=21
Function aa running 167
result: n=9;value=34
Function aa running 276
result: n=10;value=55
Function aa running 453
2,
var num=0;var bb=function(){
var arr=[0,1];
var ss=function(n){
num++;
var res=arr[n];
if(typeof res!=='number'){//当n>=2时Fibonacci数列(arr数组)才需要添加第三个
res=ss(n-1)+ss(n-2);
arr[n]=res;
document.write('Array is '+arr+'<br/>');
document.write('Function foreach count is '+num+'<br/>');
}
return res;
};
return ss;
};
var sss=bb();
for(var i=0;i<=10;i++){
document.write('result: '+'n='+i+';value='+sss(i)+'<br/>');
}
value:
result: n=0;value=0
result: n=1;value=1
Array is 0,1,1
Function foreach count is 5
result: n=2;value=1
Array is 0,1,1,2
Function foreach count is 8
result: n=3;value=2
Array is 0,1,1,2,3
Function foreach count is 11
result: n=4;value=3
Array is 0,1,1,2,3,5
Function foreach count is 14
result: n=5;value=5
Array is 0,1,1,2,3,5,8
Function foreach count is 17
result: n=6;value=8
Array is 0,1,1,2,3,5,8,13
Function foreach count is 20
result: n=7;value=13
Array is 0,1,1,2,3,5,8,13,21
Function foreach count is 23
result: n=8;value=21
Array is 0,1,1,2,3,5,8,13,21,34
Function foreach count is 26
result: n=9;value=34
Array is 0,1,1,2,3,5,8,13,21,34,55
Function foreach count is 29
result: n=10;value=55
原理:通过数组将存储结果(ss方法的值)保存,递归时直接从数组取值,不需通过再次进行递归操作得到值,减少重复递归过程