递归函数是一个自己调用的函数
它允许程序员使用最少的代码编写高效的程序。
不利的一面是,如果编写不当,它们可能会导致无限循环和其他意外结果。
我将解释简单递归函数和尾递归函数
为了写一个简单的递归函数
- 要考虑的第一点是什么时候应该决定退出 if 循环
- 第二个是如果我们是自己的函数要做什么流程
从给定的例子:
public static int fact(int n){
if(n <=1)
return 1;
else
return n * fact(n-1);
}
从上面的例子
if(n <=1)
return 1;
是何时退出循环的决定因素
else
return n * fact(n-1);
是否要进行实际处理
让我一一分解任务以便于理解。
让我们看看如果我运行内部会发生什么fact(4)
- 代入 n=4
public static int fact(4){
if(4 <=1)
return 1;
else
return 4 * fact(4-1);
}
If
循环失败,所以它进入else
循环,所以它返回4 * fact(3)
在堆栈内存中,我们有4 * fact(3)
代入 n=3
public static int fact(3){
if(3 <=1)
return 1;
else
return 3 * fact(3-1);
}
If
循环失败,所以它进入else
循环
所以它返回3 * fact(2)
记住我们调用了```4 * fact(3)`
输出为fact(3) = 3 * fact(2)
到目前为止,堆栈有4 * fact(3) = 4 * 3 * fact(2)
在堆栈内存中,我们有4 * 3 * fact(2)
代入 n=2
public static int fact(2){
if(2 <=1)
return 1;
else
return 2 * fact(2-1);
}
If
循环失败,所以它进入else
循环
所以它返回2 * fact(1)
记得我们打电话4 * 3 * fact(2)
输出为fact(2) = 2 * fact(1)
到目前为止,堆栈有4 * 3 * fact(2) = 4 * 3 * 2 * fact(1)
在堆栈内存中,我们有4 * 3 * 2 * fact(1)
代入 n=1
public static int fact(1){
if(1 <=1)
return 1;
else
return 1 * fact(1-1);
}
If
循环是真的
所以它返回1
记得我们打电话4 * 3 * 2 * fact(1)
输出为fact(1) = 1
到目前为止,堆栈有4 * 3 * 2 * fact(1) = 4 * 3 * 2 * 1
最后,fact(4) = 4 * 3 * 2 * 1 = 24
尾递归将是
public static int fact(x, running_total=1) {
if (x==1) {
return running_total;
} else {
return fact(x-1, running_total*x);
}
}
- 代入 n=4
public static int fact(4, running_total=1) {
if (x==1) {
return running_total;
} else {
return fact(4-1, running_total*4);
}
}
If
循环失败,所以它进入else
循环,所以它返回fact(3, 4)
在堆栈内存中,我们有fact(3, 4)
代入 n=3
public static int fact(3, running_total=4) {
if (x==1) {
return running_total;
} else {
return fact(3-1, 4*3);
}
}
If
循环失败,所以它进入else
循环
所以它返回fact(2, 12)
在堆栈内存中,我们有fact(2, 12)
代入 n=2
public static int fact(2, running_total=12) {
if (x==1) {
return running_total;
} else {
return fact(2-1, 12*2);
}
}
If
循环失败,所以它进入else
循环
所以它返回fact(1, 24)
在堆栈内存中,我们有fact(1, 24)
代入 n=1
public static int fact(1, running_total=24) {
if (x==1) {
return running_total;
} else {
return fact(1-1, 24*1);
}
}
If
循环是真的
所以它返回running_total
输出为running_total = 24
最后,fact(4,1) = 24的结果