查找斐波納契數(shù)列中第 N 個(gè)數(shù)。
所謂的斐波納契數(shù)列是指:
前2個(gè)數(shù)是 0 和 1 。
第 i 個(gè)數(shù)是第 i-1 個(gè)數(shù)和第i-2 個(gè)數(shù)的和。
斐波納契數(shù)列的前10個(gè)數(shù)字是:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
注意事項(xiàng)
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
代碼
- 迭代法: 時(shí)間復(fù)雜度O(n)空間復(fù)雜度O(1)
public class Solution {
/*
* @param n: an integer
* @return: an ineger f(n)
*/
public int fibonacci(int n) {
int a = 0;
int b = 1;
// 關(guān)于i < n - 1用 n 等于1, 2, 3捋一下就可確定
// n = 1 for循環(huán)迭代零次,直接返回a
// n = 2 for循環(huán)迭代一次,b 的值賦給a,返回a
// n = 3 for循環(huán)迭代兩次,第一次迭代 c 的值賦給b,第二次迭代b的值賦給a,返回a
// 寫法怎么寫都行,重要的是把對(duì)應(yīng)的值返回
for (int i = 0; i < n - 1; i++) {
int c = a + b;
a = b;
b = c;
}
return a;
}
}
- 遞歸: 時(shí)間復(fù)雜度O(2 ^ n),空間復(fù)雜度為O(2 ^ n)
public class Solution {
/*
* @param n: an integer
* @return: an ineger f(n)
*/
public int fibonacci(int n) {
if (n <= 2) {
return n - 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}
遞歸做法一般會(huì)超時(shí)