1.递归概念
什么是递归:自己调用自己,每次调用不同的量
2.递归打印
有else时,
public static void main(String[] args) {
//通过打印问题,回顾递归调用机制
test(4);
}
//打印问题.
public static void test(int n) {
if (n > 2) {
test(n - 1);
} else {
System.out.println("n=" + n);
}
}
输出结果n=2;
没有else时
public static void test(int n) {
if (n > 2) {
test(n - 1);
} //else {
System.out.println("n=" + n);
//}
}
因为调用的栈中还有n=4;n=3;n=2;递归调用规则:
- 当程序执行到一个方法时,就会开辟一个独立的空间(栈)
- 每个空间的数据(局部变量),是独立的.
输出结果:
3.递归阶乘
public static void main(String[] args) {
int res = factorial(3);
System.out.println("res=" + res);
}
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return factorial(n - 1) * n; // 1 * 2 * 3
}
}
如果是factorial(3),结果是factorial(2)3=factorial(1)23=12*3