递归的应用场景:走迷宫(回溯)
在控制台中,红色的小球需要从白色区域的左上角,走到如图所示的右下角。
问:一共有多少种不同的路线?
其中,0表示迷宫中可走的路径,1表示红色的砖块,2表示小球行走的路线。
解答: 传送门.
递归的概念:
递归就是方法自己调用自己,每次调用时传入不同的变量。递归有助于编程者解决复杂的问题,同时
可以让代码变得简洁。
可见,递归的本质就是套娃,就是复读机。
1、打印问题
问:输出什么?
public static void test(int n) {
if (n > 2) {
test(n - 1);
} // else {
System.out.println("n=" + n);
// }
}
步骤:
1)从主函数进入,遇到test方法,开辟一个独立的空间(栈)。
2)执行到test(4),仍然开辟一个独立的空间,后面同理。
3)执行到n =2时,不满足if 语句,向下执行输出语句,输出 n = 2.
输出语句执行完成之后,这个栈就相当于没了,如下图所示,但为了方便后面的叙述,暂时保留。
4)在执行完上面的操作后,依次执行每一个栈中尚未执行的输出语句。
终图:
2、阶乘问题
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return factorial(n - 1) * n;
}
}
完整代码:
package com.huey.recursion;
/**
* @author Huey 2021年2月5日下午10:08:55
*
*/
public class RecursionTest {
public static void main(String[] args) {
// 通过打印问题,回顾递归的调用机制
test(4);
int res = factorial(5);
System.out.println("res=" + res);
}
// 打印问题
public static void test(int n) {
if (n > 2) {
test(n - 1);
} // else {
System.out.println("n=" + n);
// }
}
// 阶乘问题
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return factorial(n - 1) * n;
}
}
}
测试: