关于兔子的问题

有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?

/**
 * 统计出兔子总数。
 * 
 * @param monthCount 第几个月
 * @return 兔子总数
 */
public static int getTotalCount(int monthCount)
{
    return 0;
}

因为一直兔子在生下来第三个月才会有小兔子,那么可以看为f(n)=f(n-1)+f(n-2)。此题有两个思路一个是正着算,一个是反着算。
1)正着算 从第三个月开始兔子是增加的,就等于前两个月之和
2)反着算,运用递归

#include <iostream>
using namespace std;
int fun(int n)
{
	if (n < 3)                        //运用递归计算
		return 1;
	return fun(n - 1) + fun(n - 2);
}
int main() {
	int month;
	while (cin >> month) {
		int first = 1;
		int second = 1;
		int result = 2;
		int temp;
		for (int i = 0; i < month - 3; i++)
		{
			temp = result;
			result = result + second;
			first = second;
			second = temp;
		}
		cout << result << endl;
	}
	return 0;
}

https://www.nowcoder.com/practice/1221ec77125d4370833fd3ad5ba72395?tpId=37&&tqId=21260&rp=1&ru=/activity/oj&qru=/ta/huawei/question-ranking

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值