描述:
查找斐波纳契数列中第 N 个数。
所谓的斐波纳契数列是指:
- 前2个数是 0 和 1 。
- 第 i 个数是第 i-1 个数和第i-2 个数的和。
斐波纳契数列的前10个数字是:
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.
给定 1
,返回 0
给定 2
,返回 1
给定 10
,返回 34
Java代码:
递归的方法:
从后向前的递归
class Solution {
public int fibonacci(int n) {
if (n == 1) {
return 0;
}
if (n == 2) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
非递归的方法:
数学归纳法
从前向后的计算
class Solution {
/**
* @param n: an integer
* @return an integer f(n)
*/
public int fibonacci(int n) {
// write your code here
if(n == 1){
return 0;
}
if(n == 2){
return 1;
}
int front1 = 0;
int front2 = 1;
int ret=0;
while(n > 2){
n--;
ret = front1 + front2;
front1 = front2;
front2 = ret;
}
return ret;
}
}