描述
查找斐波納契數(shù)列中第 N 個數(shù)。
所謂的斐波納契數(shù)列是指:
- 前2個數(shù)是 0 和 1 。
- 第 i 個數(shù)是第 i-1 個數(shù)和第i-2 個數(shù)的和。
- 斐波納契數(shù)列的前10個數(shù)字是:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
樣例
給定 1,返回 0
給定 2,返回 1
給定 10,返回 34
實(shí)現(xiàn)
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;
} else if (n == 2) {
return 1;
} else {
List<Integer> fibs = new ArrayList<>();
fibs.add(0);
fibs.add(1);
for (int i = 0; i < n - 2; i++) {
fibs.add(fibs.get(fibs.size() - 2) + fibs.get(fibs.size() - 1));
}
}
return fibs.get(fibs.size() - 1);
}
}
請關(guān)注我的個人網(wǎng)站:https://zhujiaqqq.github.io/