題目:古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子長到第三個月后每個月又生一對兔子,假如兔子都不死,問每個月的兔子總數為多少?
1.程序分析: 兔子的規律為數列1,1,2,3,5,8,13,21....
package org.llh.demo01;
import java.util.ArrayList;
public class DemoTest002 {
static ArrayList<Integer> list = new ArrayList();
int number ;//計算后一個月的兔子數量
public static void main(String[] args){
DemoTest002 st = new DemoTest002();
st.fun();
st.out();
}
private void fun(){ //將12個月的兔子數量保存進list鏈表集合內
list.add(1);
list.add(1); //前兩個月的兔子數量
for(int i = 3;i<=12;i++){
number = list.get(i-2)+list.get(i-3);
list.add(number);
}
}
private void out(){//輸出12個月的兔子數量
int i =1;
for(int j:list){
System.out.println("第"+(i++)+"個月的兔子數量是"+j);
}
}
}

12個月總數
package org.llh.demo01;
public class DemoTest001 {
static int MONTH[] = {1,2,3,4,5,6,7,8,9,10,11,12}; //第幾個月
static int TYPE = 1; //一對生幾對
private int getCount(int month, int type){
int sum = 0;
if(month == 1 || month ==2){
sum = 1;
}else{
sum = getCount(month - 1,1) + getCount(month - 2,1)*type;
}
return sum;
}
public static void main(String[] args) {
int count=0;
for(int a:MONTH){
int sum = (new DemoTest001()).getCount(a, TYPE);
count = sum+count;
}
System.out.println(count);
}
}

