题解 | #不死神兔问题#
不死神兔问题
http://www.nowcoder.com/practice/9fecec9c776c436b8a03ba0684ac76a7
#include <iostream>
using namespace std;
int getSum(int n);
int main() {
int n;
cin >> n;
cout << getSum(n) << endl;
return 0;
}
int getSum(int n) {
//方法二:迭代法
if(n == 1 || n == 2)
return 1;
int pre_pre=1;
int pre = 1;
int now = 0;
for(int i = 2; i < n; i++)
{
//计算当前的now,now的值为前两次之和
now = pre+pre_pre;
//更新pre和pre_pre的值
pre_pre = pre;
pre = now;
}
return now;
// 方法一:递归法
//时间复杂度:O(2^n),空间复杂度o(n)
// if(n == 1 || n == 2)
// return 1;
// return (getSum(n-1)+getSum(n-2));
}