递归

10.递归

10.1介绍

1.方法直接或者间接调用本身

2.一些算法题的实现, 都需要使用递归

10.2用递归求5的阶乘

public class MethodDemo {
   /*
       递归: 方法直接或者间接调用自己.
               - 注意: 如果递归没有设计出口, 就会出现内存溢出.

       需求: 使用递归求5的阶乘

               5的阶乘 = 5 * 4 * 3 * 2 * 1

               5! = 5 * 4!
               4! = 4 * 3!
               3! = 3 * 2!
               2! = 2 * 1!
               1! = 1
    */
   public static void main(String[] args) {

       System.out.println(jc(5));

  }

   public static int jc(int num) {
       if (num == 1) {
           return 1;
      } else {
           // num : 5
           // 5! = 5 * 4!;
           // 思路: 调用一个方法, 帮我计算4!
           // 情况: 自己这个方法就是算阶乘的
           return num * jc(num - 1);
      }
  }
}

 

10.3斐波那契数列

public class MethodTest1 {
   public static void main(String[] args) {

       System.out.println(get(20));

  }

   public static int get(int month) {
       if (month == 1 || month == 2) {
           return 1;
      } else {
           // month : 5
           // return 第三个月 + 第四个月;
           return get(month - 2) + get(month - 1);
      }
  }
}

10.4猴子吃桃

public class MethodTest2 {
   public static void main(String[] args) {

       System.out.println(monkey(1));

  }

   public static int monkey(int day) {
       //十天
       if (day == 10) {
           return 1;
      } else {
           //           9天[(9 + 1) +1]X2
           return (monkey(day + 1)  + 1) * 2;
      }
  }
}
 
posted @   灵泽pro  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示