509 Fibonacci Number 斐波那契數(shù)
Description:
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:
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.
題目描述:
斐波那契數(shù)惋啃,通常用 F(n) 表示荣赶,形成的序列稱為斐波那契數(shù)列击奶。該數(shù)列由 0 和 1 開始轴咱,后面的每一項(xiàng)數(shù)字都是前面兩項(xiàng)數(shù)字的和菱属。也就是:
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
給定 N,計(jì)算 F(N)舰罚。
示例:
示例 1:
輸入:2
輸出:1
解釋:F(2) = F(1) + F(0) = 1 + 0 = 1.
示例 2:
輸入:3
輸出:2
解釋:F(3) = F(2) + F(1) = 1 + 1 = 2.
示例 3:
輸入:4
輸出:3
解釋:F(4) = F(3) + F(2) = 2 + 1 = 3.
提示:
0 ≤ N ≤ 30
思路:
- 參考LeetCode #70 Climbing Stairs 爬樓梯
時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(1) - 通項(xiàng)公式
時(shí)間復(fù)雜度O(1), 空間復(fù)雜度O(1)
代碼:
C++:
class Solution
{
public:
int fib(int N)
{
int a = 0, b = 1;
while (N--)
{
int temp = a;
a = b;
b = temp + b;
}
return a;
}
};
Java:
class Solution {
public int fib(int N) {
switch(N) {
case 0:
return 0;
case 1:
case 2:
return 1;
case 3:
return 2;
case 4:
return 3;
case 5:
return 5;
case 6:
return 8;
case 7:
return 13;
case 8:
return 21;
case 9:
return 34;
case 10:
return 55;
case 11:
return 89;
case 12:
return 144;
case 13:
return 233;
case 14:
return 377;
case 15:
return 610;
case 16:
return 987;
case 17:
return 1597;
case 18:
return 2584;
case 19:
return 4181;
case 20:
return 6765;
case 21:
return 10946;
case 22:
return 17711;
case 23:
return 28657;
case 24:
return 46368;
case 25:
return 75025;
case 26:
return 121393;
case 27:
return 196418;
case 28:
return 317811;
case 29:
return 514229;
case 30:
return 832040;
default:
return 0;
}
}
}
Python:
class Solution:
def fib(self, N: int) -> int:
return int((5 ** 0.5) * 0.2 * (((1 + 5 ** 0.5) / 2) ** N - ((1 - 5 ** 0.5) / 2) ** N))