【JAVA】50道经典编程题

一.古典问题(斐波那契数列 or 黄金分割数列):有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

1.首先需要手算出每个月的数量以得出规律。
此处手算1-8个月即可得出数量,注意是“新couple第3个月开始才生,第4个月开始每月生一对”、“计算新一个月数量时容易遗漏已存在的旧couple”;
得到1-8个月数量:1 1 2 3 5 8 13 21;

public static void main(String[] args) {  
		int num=countRabbits(4);  
		System.out.println(num);
		}      

	public static int countRabbits(int n) {
		if(n<=2){
			return 1;         
		}return countRabbits(n-1)+countRabbits(n-2);        
	}	 

猜你喜欢

转载自blog.csdn.net/weixin_42915286/article/details/82908948
今日推荐