递归和内存分配-可视化(汉诺塔)

每一次递归调用都将过程(精确地说是“变量”)在内存中复制一遍。一旦一个过程结束(会返回一些数据),这个过程在内存中的副本就被丢弃。递归看似简单,但是可视化跟踪执行过程就很花费时间。

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);

        }
    }

}

相关链接:

https://www.cnblogs.com/programnote/p/4713416.html

https://blog.csdn.net/Marksinoberg/article/details/49531995

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值