Description
Find the Nth number in Fibonacci sequence.
A Fibonacci sequence is defined as follow:
- The first two numbers are 0 and 1.
- The i th number is the sum of i-1 th number and i-2 th number.
The first ten numbers in Fibonacci sequence is:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.
Example
Given 1
, return 0
Given 2
, return 1
Given 10
, return 34
此题有三种解法:迭代、普通递归
(1)迭代
每一次对过程的重复称为一次“迭代”,而每一次迭代得到的结果会作为下一次迭代的初始值。
int Fibonacci_1(int n) {
int pre = 0, cur = 1;
for (int i = 1; i < n; i++) {
cur += pre;
pre = cur - pre;
}
return pre;
}
注意返回值是pre。
(2)普通递归
int Fibonacci_2(int n) {
if (n == 1) return 0;
else if (n == 2) return 1;
else return Fibonacci_2(n - 1) + Fibonacci_2(n - 2);
}
代码看似简洁易于理解对吧?其实这种解法会超时。为什么?内存会为递归函数的每次调用在栈中分配一块存储空间保存函数调用信息,且递归函数调用的返回值依赖于下一次函数调用的返回值。在函数调用结束之前,所占用的堆栈资源是无法释放的,所以递归过程中会保存许多中间函数的堆栈,十分占用内存空间,经常会出现超时或者程序崩溃等异常情况。