什么是方法递归
- 递归是一种算法。
- 从形式上说,方法调用自身的形式就是方法递归。
方法递归的形式
- 直接递归:方法自己调用自己。
- 间接递归:方法调用其它方法,其它方法又回调方法自己。
使用方法递归时的注意事项
- 递归如果没有控制好终止条件,会出现死循环,导致栈内存溢出。
设计递归算法的时候要考虑:
- 递归的公式是什么,例如求阶乘的递归公式:
f(n) = n * f(n-1)
- 递归的终结点是什么,例如,求阶乘中,明确设置
f(1) = 1
,也就是说f(1)不需要再通过递归公式计算。 - 递归的方向必须走向终结点,例如,求3的阶乘:
f(3) = 3 * f(2) = 3 * 2 * f(1) = 3 * 2 * 1 = 6
示例
示例:直接递归,但没有控制好终止条件,陷入了死循环,直到堆栈溢出
package com.team.recursion;
public class Test {
public static void main(String[] args) {
test();
}
public static void test() {
System.out.println("执行到test方法中了");
test();
}
}
如果运行上面的代码,会进入死循环,直到堆栈溢出:
示例:间接递归,但没有控制好终止条件,陷入了死循环,直到堆栈溢出
package com.team.recursion;
public class Test {
public static void main(String[] args) {
test1();
}
public static void test1() {
System.out.println("执行到test1方法中了");
test2();
}
private static void test2() {
System.out.println("执行到test2方法中了");
test1();
}
}
如果运行上面的代码,会进入死循环,直到堆栈溢出:
示例:用方法递归求阶乘
package com.team.recursion;
public class Test {
public static void main(String[] args) {
System.out.println("1的阶乘等于:" + f(1));
System.out.println("2的阶乘等于:" + f(2));
System.out.println("3的阶乘等于:" + f(3));
System.out.println("4的阶乘等于:" + f(4));
System.out.println("4的阶乘等于:" + f(5));
}
public static int f(int n) {
if (n == 1) {
return 1;
} else {
return n * f(n - 1);
}
}
}
运行输出:
1的阶乘等于:1
2的阶乘等于:2
3的阶乘等于:6
4的阶乘等于:24
4的阶乘等于:120
示例:用方法递归求和
package com.team.recursion;
public class Test {
public static void main(String[] args) {
System.out.println("1到1的和 = " + f(1));
System.out.println("1到2的和 = " + f(2));
System.out.println("1到3的和 = " + f(3));
System.out.println("1到4的和 = " + f(4));
System.out.println("1到5的和 = " + f(5));
}
public static int f(int n) {
if (n == 1) {
return 1;
} else {
return n + f(n - 1);
}
}
}
运行输出:
1到1的和 = 1
1到2的和 = 3
1到3的和 = 6
1到4的和 = 10
1到5的和 = 15