递归函数是一个自己调用的函数
它允许程序员使用最少的代码编写高效的程序。
缺点是如果没有正确编写,它们可能导致无限循环和其他意想不到的结果。
我将解释简单递归函数和尾递归函数
为了写一个简单的递归函数
- 要考虑的第一点是你什么时候决定出柜
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
的结果