js 递归 汉诺塔的例子
程序调用自身的编程技巧称为递归。
//汉诺塔的游戏,n为圆盘编号数量,编号,a,b,c代表的是三个柱子
var hanio=function(n,a,b,c){
if(n>0){
hanio(n-1,a,c,b);
document.writeln('Move n '+n+" form "+a+' to '+c);
document.write("<br />");
hanio(n-1,b,a,c)
}
}
hanio(3,'a','b','c')
}
//Move n 1 form a to c
//Move n 2 form a to b
//Move n 1 form c to b
//Move n 3 form a to c
//Move n 1 form b to a
//Move n 2 form b to c
//Move n 1 form a to c
var hanio=function(n,a,b,c){
if(n>0){
hanio(n-1,a,c,b);
document.writeln('Move n '+n+" form "+a+' to '+c);
document.write("<br />");
hanio(n-1,b,a,c)
}
}
hanio(3,'a','b','c')
}
//Move n 1 form a to c
//Move n 2 form a to b
//Move n 1 form c to b
//Move n 3 form a to c
//Move n 1 form b to a
//Move n 2 form b to c
//Move n 1 form a to c
//下面是一个尾递归函数
var func=function(i,a){
a = a || 1;
if(i<2){
return a;
}
return func(i-1,a*i)
}
document.write(func(4)); //24 (1*4=4 4*3=12 12*2=24)
var func=function(i,a){
a = a || 1;
if(i<2){
return a;
}
return func(i-1,a*i)
}
document.write(func(4)); //24 (1*4=4 4*3=12 12*2=24)