標籤:
遞迴演算法設計的基本思想是:對於一個複雜的問題,把原問題分解為若干個相對簡單類同的子問題,繼續下去直到子問題簡單到可以直接求解,也就是說到了遞推的出口,這樣原問題就有遞推得解。
關鍵要抓住的是:
(1)遞迴出口
(2)地推逐步向出口逼近
範例:
example: 求5的階乘。。
例如以下:
Java代碼
- public class Test {
- static int multiply(int n){
- if(n==1||n==0)
- return n;
- else
- return n*multiply(n-1);
- }
-
- public static void main(String[] args){
- System.out.println(multiply(10));
- }
- }
public class Test { static int multiply(int n){ if(n==1||n==0) return n; else return n*multiply(n-1); } public static void main(String[] args){ System.out.println(multiply(10)); } }
上面的multiply是一個階乘的範例。事實上遞迴遞迴,從字面上解釋就是在方法本身調用自己的方法,或者間接調用;看上面的程式,拿multiply(5)來說:
n=5;運行 5*multiply(4);
--------------------
這時候看multiply(4)
n=4 運行 4*multiply(3);
-------------------
看multiply(3)
n=3,運行 3*multiply(2);
---------------
mulitply(2);
n=2 運行 2*mulitply(1);
這時候,return 1;往上返回
2*1向上返回
3*(2*1)向上返回
4*(3*(2*1)) 向上返回
5*(4*(3*(2*1)) ) = 120
所以程式輸出120;
這事簡單的遞迴的範例;所以能夠看出來遞迴的關鍵得有遞迴出口(本體的If語句),還有遞迴方法;
下面是我在百度知道碰到一個朋友的提問,也是關於遞迴演算法的:
------------------------問題------------------------------
本人剛學JAVA,沒有不論什麼編程基礎,各位高手見笑。
Java代碼
- public class Count
- {
- static void count(int n) //遞迴方法
- {
- if (n<5)
- count(n+1);
- System.out.print(" "+n);
- }
- public static void main(String args[])
- {
- count(1);
- System.out.println();
- }
- }
public class Count{ static void count(int n) //遞迴方法 { if (n<5) count(n+1); System.out.print(" "+n); } public static void main(String args[]) { count(1); System.out.println(); }}請具體解說這段程式是怎麼啟動並執行,我的理解是先運行main函數裡的count(1),然後進入count方法,N值為1,所以運行IF語句,直到count(5),此時退出if 迴圈,列印N=5 ,然後應該沒有要啟動並執行東西了,但是答案是5 4 3 2 1 ,請問這是怎麼回事,謝謝!
--------------------回答---------------------------
先運行count(1),然後進入count方法,N值為1,所以運行IF語句,也就是運行count(2),然後進入count方法,N值為2,所以運行IF語句,也就是運行count(3),然後進入count方法,N值為3,所以運行IF語句,也就是運行count(4),然後進入count方法,N值為4,所以運行IF語句,也就是運行count(5),然後進入count方法,N值為5,所以不運行IF語句,然後運行System.out.print(" "+n); 也就是輸出5,然後本次參數為5的count方法調用結束了,返回到調用它的參數為4的count方法中,然後運行System.out.print(" "+n);輸出4,然後一直這樣下去,輸出3,2,1 。這裡須要說明的是在運行count(5)的時候,count(4)、count(3)、count(2)、count(1)都沒有運行完成,他們都在等自己方法體中的count(n+1)運行完成,然後再運行System.out.print(" "+n);
Java的遞迴演算法