Java方法递归
方法递归
1.什么是方法递归
方法直接调用自己或者间接调用自己的形式称为方法递归(recursion)。递归做为一种算法在程序设计语言中广泛应用。
2.递归的形式
2.1直接递归:方法自己调用自己
2.2间接递归:方法调用别的方法,别的方法又回调自己
3.方法递归存在的问题
递归如果没有控制好终止,会出现递归死循环,导致栈内存溢出现象。
递归案例
案例一:计算1~n的阶乘
public class oneTon { public static void main(String[] args) { System.out.println(f(5)); } public static int f(int n){ if (n==1){ return 1; }else { return f(n-1)*n; } }}
运行截图
案例二:猴子吃桃问题
猴子第一天摘下若干桃子,当即吃了一半,觉得好不过瘾,于是又多吃了一个,第二天又吃了前天剩余桃子数量的一半,觉得好不过瘾,于是又多吃了一个,以后每天都是吃前天剩余桃子数量的一半,觉得好不过瘾,又多吃了一个,等到第10天的时候发现桃子只有1个了。需求:请问猴子第一天摘了多少个桃子?
/** * f(x)-f(x)/2-1=f(x+1) * 2f(x)-f(x)-2=2f(x+1) * f(x)=2f(x+1)+2 * @author JiaShuai * @date 2022/4/16 22:36 */public class Digui { public static void main(String[] args) { System.out.println(f(1)); } public static int f(int n){ if (n==10){ return 1; }else { return 2*f(n+1)+2; } }}
运行截图
非规律化案例1:文件搜索
文件搜索、从D:盘中,搜索出某个文件名称并输出绝对路径。
public class SearchFile { public static void main(String[] args) { searchFile(new File("D:/"),"收集Stream流.png"); } public static void searchFile(File dir,String fileName){ if (dir!=null&&dir.isDirectory()){ File[] files=dir.listFiles(); if (files!=null&&files.length>0){ for (File file : files) { if (file.isFile()){ if (file.getName().contains(fileName)){//是文件输出文件位置System.out.println("文件路径为:"+file.getAbsolutePath()); } }else { //是文件夹,使用递归继续找 searchFile(file,fileName); } } } }else { System.out.println("查找错误!!!"); } }}
运行截图
非规律化案例2:啤酒问题
需求:啤酒2元1瓶,4个盖子可以换一瓶,2个空瓶可以换一瓶,请问10元钱可以喝多少瓶酒,剩余多少空瓶和盖子。
public class Maijiu { public static int totalNumber; // 总数量 public static int lastBottleNumber; // 记录每次剩余的瓶子个数 public static int lastCoverNumber; // 记录每次剩余的盖子个数 public static void main(String[] args) { buy(10); System.out.println("总数:" + totalNumber); System.out.println("剩余盖子数:" + lastCoverNumber); System.out.println("剩余瓶子数:" + lastBottleNumber); } //买酒 public static void buy(int money){ // 可以直接买多少瓶 int buyNumber = money / 2; totalNumber += buyNumber; // 把盖子 和瓶子换算成钱 // 统计本轮总的盖子数 和 瓶子数 int coverNumber = lastCoverNumber + buyNumber; int bottleNumber = lastBottleNumber + buyNumber; // 统计可以换算的钱 int allMoney = 0; if(coverNumber >= 4){ allMoney += (coverNumber / 4) * 2; } lastCoverNumber = coverNumber % 4; if(bottleNumber >= 2){ allMoney += (bottleNumber / 2) * 2; } lastBottleNumber = bottleNumber % 2; if(allMoney >= 2){ buy(allMoney); } Integer[] arr2 = new Integer[]{11, 22, 33}; Arrays.sort(arr2); }}
运行截图
创作挑战赛 新人创作奖励来咯,坚持创作打卡瓜分现金大奖