描述
查找斐波纳契数列中第 N 个数.
所谓的斐波纳契数列是指:
- 前2个数是 0 和 1 。
- 第 i 个数是第 i-1 个数和第i-2 个数的和。
斐波纳契数列的前10个数字是:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
public class Solution {
/**
* @param n: an integer
* @return: an ineger f(n)
*/
public int fibonacci(int n) {
// write your code here
if (n == 1){
return 0;
}
int[] arr = new int[n];
arr[0] = 0;
arr[1] = 1;
for(int i=2;i<n;i++) {
arr[i] = arr[i-1] + arr[i-2];
}
return arr[n-1];
}
}
Error:递归实现斐波拉契数列超时
class Solution {
/**
* @param n: an integer
* @return: an ineger f(n)
*/
public int fibonacci(int n) {
// write your code here
if (n == 1){
return 0;
}else if(n == 2){
return 1;
}
return fibonacci(n-1) + fibonacci(n-2);
}
}
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 ...