查找斐波納契數(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 ...
注意事項
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
代碼
- 迭代法: 時間復雜度O(n)空間復雜度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
// 寫法怎么寫都行哮针,重要的是把對應的值返回
for (int i = 0; i < n - 1; i++) {
int c = a + b;
a = b;
b = c;
}
return a;
}
}
- 遞歸: 時間復雜度O(2 ^ n)关面,空間復雜度為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);
}
}
}
遞歸做法一般會超時