java中方法的遞歸調用

方法的遞歸調用java

 

/*
關於方法的遞歸調用
   一、什麼是遞歸?
      -方法自身調用自身
      a(){
         a(){

         }
      }
   二、遞歸是很耗費棧內存的,遞歸算法能夠不用的時候儘可能不用
   三、一下程序運行的時候發生了這樣一個錯誤【不是異常,是錯誤Error】:
      java.lang.StackOverflowErroe
      棧內存溢出錯誤。
      錯誤放生沒法挽回,只有一個結果,就是JVM中止工做
   四、遞歸必須有結束條件,沒有結束條件必定會發生棧內存溢出錯誤
   五、遞歸即便有告終束條件,即便結束條件是正確的,也可能會發生棧內存溢出錯誤,
      由於遞歸的太深了,棧內存被佔滿。
   注意:
      遞歸若是能夠不使用,儘可能不使用。
      可是有些狀況下,該功能的實現必須一覽遞歸實現,好比  目錄拷貝



*/
public class Method01{
   // 主方法
   public static void main(String[] args){
      doSome();
   } 
   // 調用doSome方法
   // 如下的代碼片斷雖然只有一份
   // 可是能夠被重複的調用,而且只要調用doSome方法就會在棧內存中開闢一塊所屬的內存空間,
   public static void doSome(){
      System.out.println("doSome begin!");
      doSome();//這行代碼不結束,下一行代碼是不能執行的
      System.out.println("doSome over!");
   }
}

 

/*
不使用遞歸計算1-N的求和【能夠不用遞歸,儘可能不用遞歸】

*/
public class Method01{
   // 主方法
   public static void main(String[] args){
      // 計算1-4的和
      // int n = 4;
      // int sum = 0;
      // for(int i=1;i<=n;i++){
      //    sum += i;
      // }
      // System.out.println(sum);

      // 直接調用方法便可
      int n = 4;
      int resultVal=sum(n);
      System.out.println(resultVal);
   } 
   // 單獨定義一個方法,這是一個獨立的功能,能夠完成1-N的求和
   public static int sum(int n){
      int result = 0;
      for(int i=1;i<=n;i++){
         result+=i;
      }
      return result;
   }
   
}

 下面用遞歸實現1-4的和,並分析內存分配狀況算法

/*
使用遞歸計算1-N的和

*/
public class Method01{
   // 主方法
   public static void main(String[] args){
      // 1-4的和
      int n = 4;
      int retValue = sum(n);
      System.out.println(retValue);
   } 
   public static int sum(int n){
      // 4+3+2+1
      if(n == 1){
         return 1;
      }
      return n + sum(n-1);
   }
   
}

 

 

/*
先不使用遞歸計算N的階乘
5的階乘:
   5*4*3*2*1

*/
public class Method01{
   // 主方法
   public static void main(String[] args){
      int n = 5;
      int retValue = method(n);
      System.out.println(retValue);//120
   } 
   public static int method(int n){
      int result = 1;
      for(int i=n;i>0;i--){
         result *= i;
      }
      return result;
   }
   
}
/*
使用遞歸計算N的階乘
5的階乘:
   5*4*3*2*1

*/
public class Method01{
   // 主方法
   public static void main(String[] args){
      int n = 5;
      int retValue = method(n);
      System.out.println(retValue);//120
   } 
   public static int method(int n){
      if(n==1){
         return 1;
      }
      return n*=method(n-=1);
   }
   
}

 遞歸內存分析:spa

 

 

 

code

相關文章
相關標籤/搜索