前言
递归指的是方法调用自己的方法但是方法最终有出口,上一项的计算基于下一次的返回值,上一项进入挂起状态等待下一项的计算结果,方法调用有最终的出口
一、递归求阶乘
5!=54321 4!=4321
可以得出5!=54!
4!=43!
3!=32!
2!=2*1
1!=1
0!=1
以上可以看出要求5的阶乘需要先知道4的阶乘,5的阶乘的计算是基于4的阶乘是一个挂起等待的状态,最终有0以下的出口
二、裴波拉数列
裴波拉数列 0 1 1 2 3 5 8 11
第0个为0
第1个为1
第2个为前两的值相加
…
/**
* 递归算法
* @author 脱发的小白
*
*/
public class Test01 {
public static void main(String[] args) {
Test01 test = new Test01();
int value=5;
int result=0;
result=test.factorial(value);
System.out.println(result);
System.out.println(test.fib(value));
}
//递归阶乘
public int factorial(int value) {
if (value >= 0) {
if (value == 0) {
return 1;
}
if (value == 1) {
return 1;
}
} else {
System.out.println("输入的值有误");
}
return value * factorial(value - 1);
}
//递归求裴波拉数列
public int fib(int value) {
if(value>=0) {
if(value==0) {
return 0;
}
if(value==1) {
return 1;
}
}
else {
System.out.println("输入的数有误");
}
return fib(value-1)+fib(value-2);
}
}
递归删除文件夹和计算文件夹大小
public class Text {
public static void main(String[] args) {
Text text = new Text();
String filePath = "D:" + File.separator + "a";
long length = text.getLength(filePath);
System.out.println(length);
text.deleteFile(filePath);
}
// 递归计算文件夹大小
public long getLength(String filePath) {
long len = 0;
File file = new File(filePath);
if (file.exists()) {
if (file.isFile()) {
len = file.length();
}
File[] listFiles = file.listFiles();
if (listFiles != null) {
for (File i : listFiles) {
len = len + getLength(i.getPath());
}
}
}
return len;
}
//删除文件夹
public void deleteFile(String filePath) {
File file = new File(filePath);
if (file.exists()) {
if (file.isFile()) {
file.delete();
}
File[] listFiles = file.listFiles();
for (File i : listFiles) {
if (i.isFile()) {
File f = i;
f.delete();
}
deleteFile(i.getPath());
}
}
file.delete();
}
}