1 / 12

第 5 章 遞迴

資料結構設計與 C++ 程式應用 Fundamentals of Data Structures and Their Applications Using C++. 第 5 章 遞迴. 資料結構設計與 C++ 程式應用 版權所有 禁止重製. 遞迴. 遞迴函數 乃是一個自己反覆呼叫自己的函數 一個典型的遞迴演算法 n! = n × (n-1)!

tamera
Télécharger la présentation

第 5 章 遞迴

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 資料結構設計與C++程式應用 Fundamentals of Data Structures and Their Applications Using C++ 第5章 遞迴 資料結構設計與C++程式應用 版權所有 禁止重製

  2. 遞迴 • 遞迴函數乃是一個自己反覆呼叫自己的函數 • 一個典型的遞迴演算法 n! = n× (n-1)! = n× (n-1) × (n-2)! = n× (n-1) ×(n-2) × (n-3)! = … = n× (n-1) ×(n-2) ×(n-3) × … ×2 ×1 1. 階乘函數一直自己呼叫自己,且引數依序由 n、n-1、n-2、…逐次遞減。 2. 當引數等於 1 時停止遞迴呼叫。

  3. 遞迴 //-------------------------------------- // n階層函數,採用遞迴演算法 //-------------------------------------- long factorial(long n) { if (n == 1) return 1; else return n * factorial(n-1) ; } //------------------------------------- // n階層函數,採用for迴路 //------------------------------------- long factorial(long n) { long f = 1; for(int i = n; i > 1; i--) f *= i; return f; }

  4. 遞迴 • 遞迴演算法需考量的因素: 1.遞迴函數的參數有哪些?每次呼叫之初值為何? 2.遞迴函數的回傳(Return)值為何? 3遞迴函數自己反覆地呼叫自己,那麼何時該結束呢?

  5. 常見的遞迴應用 • 1 費氏數列(Fibonacci) a0 = 1, a1 = 1。 an= an-1 + an-2 , 當n > 1。 // 求費氏數列第an項之值,採用遞迴演算法 long fibonacci(long n){ if(n = = 0) return 1; if(n = = 1) return 1; else return (fibonacci(n-1) + fibonacci(n-2)); }

  6. 常見的遞迴應用 • 2 求最大公因數GCD 1. 判斷兩數中哪一個比較大,大的當被除數,小的當除數。 2. 把被除數除以除數,得到商及餘數。 3. 若餘數等於 0 則 GCD = 小數。 否則 令小數成為新的被除數,餘數成為新的除數, 重複步驟 2。

  7. 常見的遞迴應用 // 求GCD之遞迴函數 int gcd(int dividend, int divisor) { int remainder ; if (dividend < divisor){ // 找出兩數之大者當被除數 swap(dividend, divisor) ;} // 小者當除數 if(divisor !=0) { remainder = dividend % divisor ; return gcd(divisor,remainder) ; } else return dividend ; } // 以參考值傳遞引數,將x,y兩數對調 void swap(int &x, int &y) { int temp = x; x = y; y = temp; }

  8. 常見的遞迴應用 • 求最大公因數GCD

  9. 常見的遞迴應用 • 3 排列 • 將1、2、3三項資料做排列之可能情形如下:

  10. 常見的遞迴應用 • 4 河內之塔:將n個碟子從a柱搬移到c柱的遞迴式 void hanoi(int n,char a, char b, char c) { int step=0; if(n > 1) hanoi(n-1, a, c, b); cout << "步驟 <" << setw(2) << ++step << "> 從 " << a << " 柱搬 " << n<< " 號碟片到 " << c << " 柱\n"; if(n > 1) hanoi(n-1, b, a, c); }

  11. 常見的遞迴應用 • 5 二元樹的追蹤和應用(請參閱第6章6.5節) • 6 遊戲樹(請參閱第6章6.8.2節) • 7 快速排序法(請參閱第8章8.2.5節)

  12. 第五章習題 • 何為遞迴程序? • 撰寫遞迴演算法需考量哪些因素? • 以非遞迴方式求兩正整數之GCD演算法為何? • 求費氏數列之非遞迴演算法為何? • 試寫出LCM(x,y)的遞迴演算法? 程式作業: 以遞迴與非遞迴方式求兩正整數的LCM(x,y)。

More Related