递归和内存分配(可视化)
2015-08-08 16:38
218 查看
每一次递归调用都将过程(精确地说是“变量”)在内存中复制一遍。一旦一个过程结束(会返回一些数据),这个过程在内存中的副本就被丢弃。递归看似简单,但是可视化跟踪执行过程就很花费时间。好了,让我们来看下面的例子:
这个例子中我们假设调用Print函数是传递的参数n=4,内存分配的图示是这样的:
![](http://i1.wp.com/www.studyalgorithms.com/wp-content/uploads/2013/10/1.png)
再来看下阶乘函数:
流程图如下:
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,内存分配的图示是这样的:
![](http://i1.wp.com/www.studyalgorithms.com/wp-content/uploads/2013/10/1.png)
再来看下阶乘函数:
//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); }
流程图如下:
![](http://i1.wp.com/www.studyalgorithms.com/wp-content/uploads/2013/10/2.png)
相关文章推荐
- [leedcode 231] Power of Two
- LeetCode(19) Remove Nth Node From End of List
- PHP实现多维数组转字符串和多维数组转一维数组的方法
- OS-4
- OpenID及其原理介绍
- Android搜索框(保存历史记录和自动匹配)带有ScrollView嵌套ListView阻尼效果
- HTML CSS的兼容性问题、IE6BUG之外边距篇
- HDU 4911
- 使用AudioPlayer播放音乐
- KEIL Memory Model
- MVC中的Html.ActionLink的介绍
- 加速器一致性接口
- 软件项目版本号的命名规则及格式
- python 当list,dic作为默认参数的正确写法
- OS-4
- Screen Property - 2
- J2EE基础Servlet
- Entity Framework 4.1 - Code First 指定外键名称
- Swift构造函数(Initializer)和析构函数(Deinitializer)
- quartz.net 时间表达式----- Cron表达式详解