介绍
方法的直接或间接调用本身
public class RecursionDemo1 {
public static void main(String[] args) {
method();
}
public static void method(){
method();
}
}
public class RecursionDemo1 {
public static void main(String[] args) {
methodA();
}
public static void methodA(){
methodC();
} public static void methodB(){
methodA();
} public static void methodC(){
methodB();
}
}
注意事项:递归如果没有控制好终止,会出现递归死循环,导致栈内存溢出现象
案例1
package com.bignyi.recursion;
public class RecursionDemo2 {
//使用递归求5的阶乘
public static void main(String[] args) {
int result = jc(5);
System.out.println(result);
}
public static int jc(int num) {
if (num == 1) {
return 1;
} else {
return num * jc(num - 1);
}
}
}
案例2
package com.bignyi.recursion;
public class RecursionDemo3 {
//使用递归求1~n的和
public static void main(String[] args) {
int result = js(3);
System.out.println(result);
}
public static int js(int num) {
if (num == 1) {
return 1;
} else {
return num + js(num - 1);
}
}
}
案例3
package com.bignyi.recursion;
public class RecursionDemo4 {
//不死死神兔
//斐波那契数列
public static void main(String[] args) {
int get = jg(3);
System.out.println(get);
}
public static int jg(int month) {
if (month == 1 || month == 2) {
return 1;
} else {
return jg(month-2) + jg(month - 1);
}
}
}
案例4
package com.bignyi.recursion;
public class RecursionDemo5 {
//猴子吃桃
public static void main(String[] args) {
int Num = eat(4);
System.out.println(Num);
}
public static int eat(int num) {
if (num == 10) {
return 1;
} else {
return (eat(num + 1) + 1) * 2;
}
}
}
递归的思路:
将大问题,层层转化为一个与原问题相似的,规模更小的问题来解决