本题考察的递归算法
/**
* 古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,
* 小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
*
* 题目分析:
* 第一个月:1对
* 第二个月:1对
* 第三个月:1+1=2对
* 第四个月: 1+1+1=3对
* 第五个月:1+1+1+1+1=5对
* 。。。
*
* 月份;
* 1 2 3 4 5 6 7 8 9
* 个数:
* 1 1 2 3 5 8 13 21
* 由分析知道 f(x)=f(x-1)+f(x-2),可知可用递归算法
* */
public class Demo01 {
//定义变量x,d=代表第几个月份
int x=1;
//创建函数求第x月份兔子的对数
public int test(int x) {
if(x==1 || x==2) {
return 1;
}
return test(x-1)+test(x-2);
}
public static void main(String[] args) {
//例如第5月份
System.out.println(new Demo01().test(5));
}
}
运行结果为:5