递归都可以用非递归代替吗?

来源:百度知道 编辑:UC知道 时间:2024/06/27 13:01:42

理论上而言,所有递归程序都可以用非递归程序来实现。

循环方法是所有递归到非递归的转换中最理想的方法,可以将开销减少到最小。不过也是分析起来最复杂的,对于简单的递归可以用这样的方法来处理。

为了理解方便,下面是用一个最简单的例子:求N的阶乘。
递归的方法:
int Factorial(int n){
if( n > 1){
return n*Factorial(n-1);//递归函数调用
}
else if(n == 1){
return 1; //递归出口
}
else{
return ERROR;//报告输入错误
}
}
转为非递归的方法:
Factorial(int n){
int k = 1 ;//增量
int t = 1 ;//临时结果
while(k!=n){
t*=k;
k++;
}
return t;
}

会变得很复杂吧.为什么要转呢,我很喜欢递归.