【算法 Java】递归,阶乘的递归实现,斐波那契数列的递归实现

递归

定义:方法直接或间接地调用方法本身
思路:将大问题转化为一个与原问题相似的规模更小的问题
注意:递归死循环会导致栈内存溢出

一些使用递归求解的问题

阶乘

Factorial.java
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int fac = getFactorial(x);
System.out.println(fac);
}
private static int getFactorial(int x) {
if(x == 1) return x;
return x * getFactorial(x - 1);
}
}

斐波那契数列

模板题:牛客-Fibonacci数列

Fibonacci.java
import java.util.Scanner;
public class Fibonacci {
private static final int MOD = 10007;
private static int[] res = new int[1000001];
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
for(int i = 1; i <= x; ++ i ) {
res[i] = -1;
}
fibonacci(x);
System.out.println(res[x]);
}
private static int fibonacci(int x) {
if(res[x] != -1) return res[x];
if(x == 1 || x == 2) return res[x] = 1;
return res[x] = (fibonacci(x - 1) + fibonacci(x - 2)) % MOD;
}
}
posted @   沙汀鱼  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
点击右上角即可分享
微信分享提示