509. Fibonacci Number
[Easy] “Return the nth Fibonacci number."
Python3:
class Solution:
def fib(self, N: int) -> int:
x1 = 0
x2 = 1
if N == 0:
return x1
elif N == 1:
return x2
else:
res = x1
while N > 1:
res = x1 + x2
x1 = x2
x2 = res
N -= 1
return res
# def fib(self, N: int) -> int:
# if N == 0:
# return 0
# elif N == 1:
# return 1
# else:
# return self.fib(N - 1) + self.fib(N - 2)
# def fib(self, N: int) -> int:
# cache = {}
#
# def cache_fib(N):
# if N in cache:
# return cache[N]
# if N == 0:
# res = 0
# elif N == 1:
# res = 1
# else:
# res = cache_fib(N - 1) + cache_fib(N - 2)
# # put result in cache for later reference.
# cache[N] = res
# return res
# return cache_fib(N)