優勢: 簡潔+裝B
代價:函數調用+系統棧空間
另外:使用遞歸,代碼易不易讀,這要因人而異,水平高的可能認爲遞歸很易讀,不遞歸反而羅裏吧嗦的麻煩。
遞歸函數感受就是本身調用本身,最後給本身一個臺階下
在此以前最好了解一下棧的機制:可參考:04-圖解數據結構之棧--Stackgit
/** * 做者:張風捷特烈 * 時間:2018/9/20 0020:16:45 * 郵箱:1981462002@qq.com * 說明:一個簡單的吃蘋果遞歸 */ public class AppleEaterClient { public static void main(String[] args) { Apple apple = new Apple(5); eat(apple); //蘋果還剩4口 //蘋果還剩3口 //蘋果還剩2口 //蘋果還剩1口 //蘋果還剩0口 //蘋果吃完了 } private static void eat(Apple apple) { if (apple.size <= 0) { System.out.println("蘋果吃完了"); return; } apple.size = apple.size - 1; System.out.println("蘋果還剩" + apple.size + "口"); eat(apple); } private static class Apple { public int size; public Apple(int size) { this.size = size; } } }
/** * 做者:張風捷特烈 * 時間:2018/10/6 0006:21:46 * 郵箱:1981462002@qq.com * 說明:2306====>依次打印2 3 0 6 */ public class PrintInt { public static void main(String[] args) { printInt(2306); } private static void printInt(int num) { if (num <= 0) { return; } printInt(num / 10); System.out.println(num % 10); } }
/** * 做者:張風捷特烈 * 時間:2018/9/20 0020:16:56 * 郵箱:1981462002@qq.com * 說明:遞歸求數組和 */ public class Sum { public static int sum(int[] arr) { return sum(arr, 0); } /** * 遞歸函數 * @param arr 數組 * @param start 開始位置 * @return 從開始位置到最後全部元素和 */ private static int sum(int[] arr,int start) { if (start == arr.length) {//終結點 return 0; } return arr[start] + sum(arr, start + 1); } public static void main(String[] args) { System.out.println(sum(new int[]{1, 2, 3, 4})); } }
/** * 做者:張風捷特烈 * 時間:2018/10/10 0010:15:23 * 郵箱:1981462002@qq.com * 說明:將一個十進制轉換爲n進制 */ public class ScaleTo { public static void main(String[] args) { scaleTo(77772, 2);//10010111111001100 scaleTo(77772, 8);//227714 scaleTo(77772, 16);//12FCC } /** * 將一個十進制轉換爲n進制 * * @param num 數字 */ private static void scaleTo(int num, int n) { char[] chars = new char[]{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; if (num == 0) { return; } scaleTo(num / n, n); int i = num % n; System.out.print(chars[i]); } }
結合棧結構,對遞歸debug一步步調試,或者本身畫畫圖,更容易明白遞歸是怎麼一步步走的,這是很是重要的。對於樹的操做少不了遞歸,若是對遞歸有絲毫疑惑,那後面將會步履維艱。遞歸是一個小小的高山,是須要認真爬過去的,馬馬虎虎就想過去,不存在的。下一部分就將對二叉樹全面進攻。github
項目源碼 | 日期 | 備註 |
---|---|---|
V0.1--無 | 2018-10-2 | 06--圖解數據結構之遞歸小例子 |
V0.2--無 | 2018-10-10 | 添加:將一個十進制轉換爲n進制的遞歸 |
筆名 | 微信 | 愛好 | |
---|---|---|---|
張風捷特烈 | 1981462002 | zdl1994328 | 語言 |
個人github | 個人簡書 | 個人CSDN | 我的網站 |
1----本文由張風捷特烈原創,轉載請註明編程
2----歡迎廣大編程愛好者共同交流
3----我的能力有限,若有不正之處歡迎你們批評指證,一定虛心改正
4----看到這裏,我在此感謝你的喜歡與支持數組