递归算法的关键
1.f(n)和f(n+1) 或f(n)和f(n-1)之间的关系公式
2.递归的中止条件
3.递归的方法必须朝向中止条件
猴子吃桃问题
分析递归公式: f(x)-f(x)/2-1=f(x+1)
中止条件: f(10)=1
代码示例
public class Demo01 {
public static void main(String[] args) {
System.out.println(f(1));
}
public static int f(int i){
if(i==10){
return 1;
}else{
return 2*f(i+1)+2;
}
}
}
非规律化递归:文件搜索问题
package com.recursion;
import java.io.File;
import java.io.IOException;
/*
目标:去D盘搜索一个文件 Wallpaper Engine
*/
public class Demo02 {
public static void main(String[] args) {
//2.传入目录和文件名称
searchFile(new File("D:/"),"Telegram.exe");
}
/**
* 1.搜索某个目录下的全部文件,找到想要的文件
* @param dir 被搜索的目录
* @param fileName 想要的文件名
*/
public static void searchFile(File dir,String fileName){
//3.判断dir是否是目录
if(dir!=null&&dir.isDirectory()){
//可以找了
//4.判断当前目录下的一级文件对象
File[] files = dir.listFiles(); //文件夹没有权限返回null,文件夹什么都没有返回空数组[]
//5.判断是否一级文件对象
if(files!=null&&files.length>0){
for (File file : files) {
//6.判断当前遍历的一级文件对象是文件还是目录
if(file.isFile()){
//7.是不是想要找到,是输出路径
if (file.getName().contains(fileName)){
System.out.println("找到了"+file.getAbsolutePath());
// //拓展:启动它
// try {
// Runtime r = Runtime.getRuntime();
// r.exec(file.getAbsolutePath());
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}else{
//8.是文件夹,需要继续递归查找
searchFile(file,fileName);
}
}
}
}else{
System.out.println("对不起,当前搜索的位置不是文件夹");
}
}
}
拓展案例:啤酒问题
package com.recursion;
/*
啤酒问题
*/
public class Demo03 {
//定义一个静态变量用于储存可以买的数量
public static int sum = 0;
public static int lastBottle = 0; //剩余的瓶子个数
public static int lastCover = 0; //剩余的盖子个数
public static void main(String[] args) {
//1.拿钱买酒
buy(10);
}
public static void buy (int money) {
//2.看可以立马买多少瓶
int buyNumber = money / 2;
sum += buyNumber;
//3.把盖子和瓶子换算成钱
//统计本轮总的盖子数 和 瓶子数
int coverNumber = lastCover + buyNumber;
int bottleNumber = lastBottle + buyNumber;
//统计可以换算的钱
int allMoney = 0;
if (coverNumber >= 4) {
allMoney += (coverNumber / 4) * 2;
}
lastCover = coverNumber % 4;
if (bottleNumber >= 2) {
allMoney += (bottleNumber / 2) * 2;
}
lastBottle = bottleNumber % 2;
if (allMoney >= 2) {
buy(allMoney);
} else {
System.out.println("买的啤酒数量为" + sum);
System.out.println("剩余的瓶盖为" + lastCover);
System.out.println("剩余的瓶子为" + lastBottle);
}
}
}