image.png
    image.png
    image.png
    从栈内存,从下往上加载
    image.png
    最后f(1) 到了终结点后返回1,方法消失,进入f2 = 2 * f(1) 一直按照规律执行下去
    image.png
    最后返回给变量result
    image.png

    1. package com.itheima.d2_recusion;
    2. /**
    3. * 目标:递归的算法和执行流程
    4. */
    5. public class RecursionDemo02 {
    6. public static void main(String[] args) {
    7. System.out.println(f(5)); //120
    8. }
    9. // 按照规则定义一个计算方法
    10. public static int f(int n){ // 内部计算方法 f(n) = 1 * 2 * 3 * 4 * ...(n-1) * n
    11. // 等价于 f(n) = f(n-1) * n
    12. if (n == 1){ // 终结点 递归的反向必须走向终结点 下面的语句,最后都走向终结点
    13. return 1;
    14. }else {
    15. return f(n-1) * n; // 首先f5进入这个分支变成f4 * n 这里又调用了f方法(相当于自己调用自己 -- 递归)
    16. }
    17. }
    18. }