關於遞歸方法的實現

所謂遞歸(Rcursion),就是方法調用自身.對於遞歸來講,必定有一個出口,讓遞歸結束,只有這樣才能保證不出現死循環.算法

一些複雜的應用遞歸仍是挺難的,好比在調試的時候A調用B,直接去B看就好了,可是遞歸的話調試的時候又去A了.對思惟要求仍是比較高的.數組

好比:n! = n * (n-1) * (n-2)......*1 另一種思路是用遞歸的思想 n! =  n * (n-1) !spa

遞歸很容易出錯,稍微不注意就變成死循環了.調試

1.計算一個數階乘的遞歸算法:code

 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個斐波那契數列是幾?blog

 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 }
相關文章
相關標籤/搜索