JAVA_SE基礎——18.方法的遞迴

來源:互聯網
上載者:User

標籤:遞迴演算法   遞迴   java   局部變數   執行個體   

方法的遞迴是指在一個方法的內部調用自身的過程,遞迴必須要有結束條件,不然就會陷入無限遞迴的狀態,永遠無法結束調用,接下來用一個最簡單的例子來體現下方法遞迴,使用遞迴演算法計算自然數之和:

public class Example18 {<span style="white-space:pre"></span>public static void main(String[] args) {<span style="white-space:pre"></span>int sum = getSum(4);                    // 調用遞迴方法,獲得1~4的和<span style="white-space:pre"></span>System.out.println("sum = " + sum); // 列印結果<span style="white-space:pre"></span>}<span style="white-space:pre"></span>// 下面的方法使用遞迴實現 求1~n的和<span style="white-space:pre"></span>public static int getSum(int n) {<span style="white-space:pre"></span>if (n == 1) {<span style="white-space:pre"></span>// 滿足條件,遞迴結束<span style="white-space:pre"></span>return 1;<span style="white-space:pre"></span>}<span style="white-space:pre"></span><span style="white-space:pre"></span>return n+getSum(n - 1);<span style="white-space:pre"></span>}}
結果是:sum = 10

本人初學者,我用口述下上面代碼的解釋,如有誤請提出, 我直接從求和的方法解釋吧   

if (n == 1)   這是條件  如果n等於1 就返回1

<pre name="code" class="java">return n+getSum(n - 1);

第一次遞迴 4+(4-1) 第二次遞迴4+(3-1)  第二次遞迴4+(2-1)  第四次滿足條件 直接返回1    那個n=4 一直沒有改變過   接著加上 1+2+3+4=10
 

再講一個階乘的例子,代碼如下:

public class Example018 {      <span style="white-space:pre"></span>static int multiply(int n){      <span style="white-space:pre"></span>if(n==1) {     <span style="white-space:pre"></span>return n;      <span style="white-space:pre"></span>}<span style="white-space:pre"></span>return n*multiply(n-1);      }         <span style="white-space:pre"></span>public static void main(String[] args){      <span style="white-space:pre"></span>System.out.println(multiply(3));      }      }    
這代碼的需求是1~3相乘

if(n==1)

if如果等於1 就返回1

return n*multiply(n-1);
n=3   3*(3-2)*(2-1)*1  


看完還不懂的留言或加我企鵝吧  654249738   




著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

JAVA_SE基礎——18.方法的遞迴

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.