生兔子遞歸算法:
public class RabbitTest { public static void main(String[] args) { /* 例題: 有一對兔子,從出生後第3個月起每個月都生一對兔子,小兔子長到第三個月後每個月又生一對兔子。假如兔子都不死,要求輸出一年內兔子的數量是多少。 分析: 該題是典型的斐波那契數列的一個實例應用。 我們可以先把前幾月的兔子數手動算出來尋找規律: 即:1 1 2 3 5 8…… 13 21 34 55 89 144 由前幾個月的兔子數可以推出:f(n)= f(n-1)+f(n-2) {n 代表月份} */ int month = 12; int result = rabbitProduce(month); System.out.println(result); } private static int rabbitProduce(int month) { if(month == 1 || month == 2){ return 1; } return rabbitProduce(month - 1) + rabbitProduce(month - 2); } }