/** 遞歸的原則: 1. 基準情形; 2. 不斷推進; 3. 設計法則; 4. 合成效益法則 2.遞歸實例:判斷當傳入的數字一直遞歸到1.組合成字符串輸出 以下通過 錯誤和正確的寫法對比學習 */
/** * 錯誤的遞歸 */ private String testRecursive1(String str,Integer inte){ str = str + inte.toString(); //如果滿足條件就遞歸 if(inte>1){ inte = inte - 1; testRecursive1(str,inte); } return str; }
@Test public void testFun(){ System.out.println(testRecursive1("得到的數據是:",5)); } 測試結果如下:
得到的數據是:5
Process finished with exit code 0 在debug過程中可以看到先遞歸到 1,str=得到的數據是:54321,接着就return,在到父函數return,然後再祖父函數return。。。 最後return到第一級方法,即輸出 “得到的數據是:5”
/** * 正確的可以return的遞歸函數 */ private String testRecursive2(String str,Integer inte){ str = str + inte.toString(); //如果滿足條件就遞歸 if(inte>1){ inte = inte - 1; return testRecursive2(str,inte); } return str; }
@Test public void testFun(){ System.out.println(testRecursive2("得到的數據是:",5)); }
測試結果如下:得到的數據是:54321
Process finished with exit code 0