递归:自己调用自己 两种方式: 直接调用:自己调用自己 间接调用:别人调用自己 递归原理: 下一层方法依次调用第一层方法 找到终点,然后用终点的值,逆推回最初的第一层方法, 代入后输出结果 method(5) = 5 + method(5-1); method(4) = 4 + method(4-1); method(3) = 3 + method(3-1); method(2) = 2 + method(2-1); method(1) = 1; 得到终点的最终返回值。逆推回去 method(1) = 1; method(2) = 2 + 1 = 3; method(3) = 3 + 3 = 6; method(4) = 4 + 6 = 10; method(5) = 5 + 10 = 15; 输出 method = 15;
public class RecursionDemo {
public static void main(String[] args) {
int n= 5;
int sum = method(n);
System.out.println(sum);
}
//method方法递归调用自己
public static int method(int n){
if (n == 1){
return 1;
}
return n + method(n-1);
}
}