一、概念
自己调用自己。
二、举例
1、打印问题
public class RecursionTest {
public static void main(String[] args) {
test(4);
}
public static void test(int n) {
if (n > 2) {
test(n - 1);
}
System.out.println("n=" + n);
}
}
结果
n=2
n=3
n=4简单解释下:方法是存放到jvm的栈空间中的,栈先入后出,所以先入的4在最后出,最后入的2最先出。
2、阶乘问题
package com.chentongwei.struct.recursion;
/**
* Description:
*
* @author TongWei.Chen 2019-12-25 10:37:12
*/
public class RecursionTest {
public static void main(String[] args) {
System.out.println(factorial(5));
}
public static int factorial(int n) {
if (n == 1) {
return 1;
}
return factorial(n - 1) * n;
}
}
结果
120
也就是:1 x 2 x 3 x 4 x 5=120
三、图解递归
拿打印问题举例说明
public static void test(int n) { if (n > 2) { test(n - 1); } System.out.println("n=" + n); }
1、通俗易懂的解释
比如传进去的是4,我们把调用自己拆分成调用其他方法,那不就是:
// n=4
public static void test(int n) {
if (n > 2) {
test1(n - 1);
}
System.out.println("n=" + n);
}
// n=3
public static void test1(int n) {
if (n > 2) {
test2(n - 1);
}
System.out.println("n=" + n);
}
// n=2
public static void test2(int n) {
if (n > 2) {
test1(n - 1);
}
System.out.println("n=" + n);
}
所以最后结果:2 3 4。这种解释简单粗暴。下面详细图解下
2、图解
扫描二维码关注公众号,回复:
10080863 查看本文章
文字解释:
1.main函数入栈
2.main函数调用的test(4)入栈
3.test(4)的4大于2,调用test(4-1)
4.test(3)入栈,3大于2,调用test(3-1)
5.test(2)入栈,2不大于2,所以直接走Sys,输出2
6.test(2)执行结束,出栈
7.test(3)是栈顶,开始继续执行,Sys(因为test(3-1)执行完了,所以继续执行Sys),输出3
8.test(3)执行结束,出栈
9.test(4)是栈顶,开始继续执行,Sys(因为test(4-1)执行完了,所以继续执行Sys),输出4
10.test(4)执行结束,出栈
11.main方法结束,退出程序
四、递归法则
- 执行一个方法时,就创建一个新的受保护的独立空间(栈空间)。
- 方法的局部变量是独立的,不会相互影响。也就是栈是线程私有的。
- 递归必须向退出递归的条件逼近,否则就是无限递归(出现StackOverflowError)。
- 当一个方法执行完毕,或者遇到return,就会返回。遵守谁调用,就将结果返回给谁的理念。