目录
1.题目描述
有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?
2.解题思路
通过计算前几个月的兔子总数,我们不难发现:以后每个月的兔子总数呈斐波那契数,所以就不难下手--用递归的方法解决!!即getTotalCount(monthCount-1)+getTotalCount(monthCount-2);
3.代码实现
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int num = sc.nextInt();
System.out.println(getTotalCount(num));
}
//sc.close();
}
public static int getTotalCount(int monthCount){
if(monthCount == 1 || monthCount == 2){
return 1;
}
return getTotalCount(monthCount-1)+getTotalCount(monthCount-2);
}
}