递归方法的实现阶乘,删除文件夹中所有文件和斐波那契数列

所谓递归(Rcursion),就是方法调用自身.对于递归来说,一定有一个出口,让递归结束,只有这样才能保证不出现死循环.

一些复杂的应用递归还是挺难的,比如在调试的时候A调用B,直接去B看就行了,但是递归的话调试的时候又去A了.对思维要求还是比较高的.

比如:n! = n * (n-1) * (n-2)......*1 另外一种思路是用递归的思想 n! =  n * (n-1) !

递归很容易出错,稍微不注意就变成死循环了.

1.计算一个数阶乘的递归算法:

 1 public class Factorial2 {
 2     //使用递归的方式计算阶乘
 3     public static void main(String[] args) {
 4         compute(5);
 5     }
 6     public static  int compute(int number){
 7         if(1 == number){
 8             return 1;
 9         }else{
10             return number * compute(number-1);
11         }
12     }
13 }

2.用递归计算第n个斐波那契数列是几?

 1 public class Factorial3 {
 2     //使用递归计算斐波那契数列.
 3     public static int compute(int n){
 4         //递归的出口
 5         if(1==n || 2==n){
 6             return 1;
 7         }else{
 8             return compute(n-1)+compute(n-2);
 9         }
10     }
11     public static void main(String[] args) {
12         System.out.println(compute(9));
13     }
14 }

3.用递归删除一个文件夹.

 1 public class Factorial4 {
 2     //用递归的方法删除文件.
 3     public static void main(String[] args) {
 4         deleteAll(new File("C:\kongtest"));
 5     }
 6     
 7     public static void deleteAll(File file){
 8         //如果这个是一个文件或者不是文件(那就是个目录里面为空)中的list()返回一个数组的长度是0
 9         if(file.isFile() || file.list().length == 0){
10             file.delete();
11         }else{
12             File[] files = file.listFiles();
13             for(File f:files){
14                 deleteAll(f);
15                 f.delete();
16             }
17         }
18     }
19 }
原文地址:https://www.cnblogs.com/DreamDrive/p/4083841.html