ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
>[success] # 递归练习 * 递归本质就是指在方法体的内部**直接或间接调用当前方法自身**的形式 * 递归必须有递归的规律以及**退出条件** >[danger] ##### 实现数n的阶乘 ~~~ public class SumTest { // 非递归 int factorial(int num) { int sum = 1; for (int i = 1; i <= num; i++) { sum *= i; } return sum; } // 使用递归 int recursionFactorial(int num) { if (num == 1) { return 1; } return num * recursionFactorial(num - 1); } public static void main(String[] args) { SumTest sumTest = new SumTest(); int a = sumTest.factorial(5); // 120 int b = sumTest.recursionFactorial(5); // 120 System.out.println(a + "," + b); } } ~~~ >[danger] ##### 斐波那契数列 * 非递归思路 ![](https://img.kancloud.cn/bb/eb/bbebdd00e516460465470f22e9a954fe_1258x524.png) ~~~ public class SumTest { // 非递归 利用指针 int fibonacci(int index) { int a = 1; int b = 1; int c = b; while (index >= 3) { b = a + c; a = c; c = b; index--; } return b; } // 使用递归 int recursionFibonacci(int index) { if (index == 1 || index == 2) { return 1; } return recursionFibonacci(index - 1) + recursionFibonacci(index - 2); } public static void main(String[] args) { SumTest sumTest = new SumTest(); int a = sumTest.fibonacci(6); // 8 int b = sumTest.recursionFibonacci(6); // 8 System.out.println(a + "," + b); } } ~~~