Java教程-Java 中的递归

在Java中,递归是指一个方法不断地调用自身的过程。被调用自身的方法称为递归方法。
递归方法的特点是能够通过较少的代码实现复杂的逻辑,使代码更加简洁。然而,递归方法有时也难以理解和调试,因为它涉及到方法的嵌套调用,可能会造成代码执行流程不易跟踪和理解。在编写递归方法时,需要仔细考虑递归的终止条件,以避免无限循环和栈溢出等问题。
递归在某些情况下是非常有用的,特别是对于处理具有递归结构的问题或数据结构,如树、图等。然而,对于简单的问题,使用迭代方法可能更易于理解和实现。在使用递归时,需要权衡代码的简洁性和可读性,确保递归方法能够正确地终止和返回期望的结果。
句法:
returntype methodname(){
//要执行的代码
methodname();//调用相同的方法
}
Java 递归示例 1:无限
public class RecursionExample1 {
static void p(){
System.out.println("hello");
p();
}
public static void main(String[] args) {
p();
}
}
输出:
hello
hello
...
java.lang.StackOverflowError
Java 递归示例 2:有限
public class RecursionExample2 {
static int count=0;
static void p(){
count++;
if(count<=5){
System.out.println("hello "+count);
p();
}
}
public static void main(String[] args) {
p();
}
}
输出:
hello 1
hello 2
hello 3
hello 4
hello 5
Java 递归示例 3:阶乘数
public class RecursionExample3 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args) {
System.out.println("Factorial of 5 is: "+factorial(5));
}
}
输出:
Factorial of 5 is: 120
上述程序的工作:
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120
Java 递归示例 4:斐波那契数列
public class RecursionExample4 {
static int n1=0,n2=1,n3=0;
static void printFibo(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibo(count-1);
}
}
public static void main(String[] args) {
int count=15;
System.out.print(n1+" "+n2);//打印0和1
printFibo(count-2);//n-2 因为已经打印了 2 个数字
}
}
输出:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377