The Fibonacci numbers, commonly denoted F(n)
form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0
and 1
. That is,
F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), for N > 1.
Given N
, calculate F(N)
.
Example 1:
Input: 2 Output: 1 Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Example 2:
Input: 3 Output: 2 Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
Example 3:
Input: 4 Output: 3 Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
Note:
0 ≤ N
≤ 30.
這道題是關於斐波那契數列的,這個數列想必我們都聽說過,簡而言之,除了前兩個數字之外,每個數字等於前兩個數字之和。舉個生動的例子,大學食堂里今天的湯是昨天的湯加上前天的湯。哈哈,是不是瞬間記牢了。題目沒讓返回整個數列,而是直接讓返回位置為N的數字。那么還是要構建整個斐波那契數組,才能知道位置N上的數字。像這種有規律有 pattern 的數組,最簡單的方法就是使用遞歸啦,先把不合規律的前兩個數字處理了,然后直接對 N-1 和 N-2 調用遞歸,並相加返回即可,參見代碼如下:
解法一:
class Solution { public: int fib(int N) { if (N <= 1) return N; return fib(N - 1) + fib(N - 2); } };
上面的寫法雖然簡單,但是並不高效,因為有大量的重復計算,我們希望每個值只計算一次,所以可以使用動態規划 Dynamic Programming 來做,建立一個大小為 N+1 的 dp 數組,其中 dp[i] 為位置i上的數字,先初始化前兩個分別為0和1,然后就可以開始更新整個數組了,狀態轉移方程就是斐波那契數組的性質,最后返回 dp[N] 即可,參見代碼如下:
解法二:
class Solution { public: int fib(int N) { if (N <= 1) return N; vector<int> dp(N + 1); dp[0] = 0; dp[1] = 1; for (int i = 2; i <= N; ++i) { dp[i] = dp[i - 1] + dp[i - 2]; } return dp[N]; } };
我們可以對上面解法進行空間上的進一步優化,由於當前數字只跟前兩個數字有關,所以不需要保存整個數組,而是只需要保存前兩個數字就行了,前一個數字用b表示,再前面的用a表示。a和b分別初始化為0和1,代表數組的前兩個數字。然后從位置2開始更新,先算出a和b的和 sum,然后a更新為b,b更新為 sum。最后返回b即可,參見代碼如下:
解法三:
class Solution { public: int fib(int N) { if (N <= 1) return N; int a = 0, b = 1; for (int i = 2; i <= N; ++i) { int sum = a + b; a = b; b = sum; } return b; } };
給下面的這種解法跪了,直接 hardcode 了所有N范圍內的斐波那契數字,然后直接返回,這尼瑪諸葛孔明的棺材板快壓不住了。。。我從未見過如此。。。
解法四:
class Solution { public: int fib(int N) { vector<int> fibs{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040}; return fibs[N]; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/509
類似題目:
Split Array into Fibonacci Sequence
Length of Longest Fibonacci Subsequence
參考資料:
https://leetcode.com/problems/fibonacci-number/
https://leetcode.com/problems/fibonacci-number/discuss/215992/Java-Solutions
https://leetcode.com/problems/fibonacci-number/discuss/216245/Java-O(1)-time