每一次递归调用都将过程(精确地说是“变量”)在内存中复制一遍。一旦一个过程结束(会返回一些数据),这个过程在内存中的副本就被丢弃。递归看似简单,但是可视化跟踪执行过程就很花费时间。
private int Print(int n)
{
if(n == 0) {
return 0;
}
else {
printf("%d",n);
return Print(n-1); // recursive call to itself again
}
}
这个例子中我们假设调用Print函数是传递的参数n=4,内存分配的图示是这样的:
再来看下阶乘函数:
int Fact(int n)
{
//base case: factorial of 0 or 1 is 1
if(n == 1)
return 1;
else if(n == 0)
return 1;
//recursive case: multiply n by (n-1) factorial
else
return n*Fact(n-1);
}
流程图如下:
使用递归解决汉诺塔问题:
public class HanoiTest {
static long endTime;
public static void main(String []args){
int n=4;
long currentTime=System.currentTimeMillis();
Function(n,"A","B","C");
endTime=System.currentTimeMillis();
System.out.println("共用时:"+(endTime-currentTime)/1000+"秒");
}
/*
* 递归思路:
* 1、当n等于1时,直接将A移动到C上
* 2、先拿C作为过渡,把A上的n-1个移动到B上,然后把A上的最后一个移动到C上,在拿A做过渡,将B上的所有的移动到C上
* 3、这将会自动的实现递归的过程并解决问题
*/
public static void Function(int n,String a,String b,String c){
if(n==1){
System.out.println("Move "+ a+" to "+c);
}else{
Function(n-1, a, c, b);
System.out.println("Move "+ a+" to "+c);
Function(n-1, b, a, c);
}
}
}
相关链接: