zoukankan      html  css  js  c++  java
  • 递归和内存分配(可视化)

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

    int Print(int n) //print numbers 1 to n backwards
    {
        if(n == 0)
            return 0;
        else
        {
            printf("%d",n);
            return Print(n-1); //recursive call to itself again
        }
    }

    这个例子中我们假设调用Print函数是传递的参数n=4,内存分配的图示是这样的:

    再来看下阶乘函数:

    //calculates the factorial of a positive integer
    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);
    }

    流程图如下:

  • 相关阅读:
    CSS快速入门
    Kafka (一) 核心概念
    软件工程模型
    函数式编程
    spark计算操作整理
    HBase 文件合并
    HBase 数据存储结构
    目的论浅谈
    PHP8的注解
    JS的移入移除
  • 原文地址:https://www.cnblogs.com/programnote/p/4713416.html
Copyright © 2011-2022 走看看