Skip to content

Commit b4ccce1

Browse files
committed
Fibonacci Number
1 parent 9ff0e1b commit b4ccce1

File tree

1 file changed

+11
-14
lines changed

1 file changed

+11
-14
lines changed

509-fibonacci-number.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
"""
22
Problem Link: https://leetcode.com/problems/fibonacci-number/
33
4-
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is
5-
the sum of the two preceding ones, starting from 0 and 1. That is,
4+
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence,
5+
such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
66
F(0) = 0, F(1) = 1
77
F(N) = F(N - 1) + F(N - 2), for N > 1.
88
Given N, calculate F(N).
@@ -25,16 +25,13 @@
2525
Note:
2626
0 ≤ N ≤ 30.
2727
"""
28+
# Time Complexity: O(N)
29+
# Space Complexity: O(1)
2830
class Solution:
29-
def fib(self, N):
30-
"""
31-
:type N: int
32-
:rtype: int
33-
"""
34-
if N == 0:
35-
return 0
36-
l = [0,1]
37-
for i in range(2,N):
38-
s = l[i-1] + l[i-2]
39-
l.append(s)
40-
return l[N-1] + l[N-2]
31+
def fib(self, N: int) -> int:
32+
if N <= 1:
33+
return N
34+
a, b = 0, 1
35+
for _ in range(2, N+1):
36+
a, b = b, a + b
37+
return b

0 commit comments

Comments
 (0)