2021-03-07 21:32:55 +01:00
|
|
|
# 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,
|
2021-03-07 22:00:10 +01:00
|
|
|
#
|
2021-03-07 21:32:55 +01:00
|
|
|
# F(0) = 0, F(1) = 1
|
2021-03-07 21:54:10 +01:00
|
|
|
# F(n) = F(n - 1) + F(n - 2), for n > 1
|
|
|
|
#
|
2021-03-07 21:32:55 +01:00
|
|
|
# Given n, calculate F(n).
|
|
|
|
|
|
|
|
#
|
2021-03-07 21:34:50 +01:00
|
|
|
# Approach: Top-Down Approach using Memoization
|
2021-03-07 21:32:55 +01:00
|
|
|
#
|
|
|
|
|
|
|
|
# Complexity Analysis:
|
|
|
|
#
|
2021-03-07 21:34:50 +01:00
|
|
|
# Time complexity: O(n). Each number, starting at 2 up to and
|
|
|
|
# including N, is visited, computed and then stored for O(1) access
|
|
|
|
# later on.
|
2021-03-07 21:54:10 +01:00
|
|
|
#
|
2021-03-07 21:34:50 +01:00
|
|
|
# Space complexity: O(n). The size of the stack in memory is
|
|
|
|
# proportionate to N.
|
2021-03-07 21:32:55 +01:00
|
|
|
#
|
2021-03-07 22:00:10 +01:00
|
|
|
def fibonacci(number, memo_hash = {})
|
|
|
|
return number if number <= 1
|
2021-03-07 21:32:55 +01:00
|
|
|
|
2021-03-07 22:00:10 +01:00
|
|
|
memo_hash[0] = 0
|
|
|
|
memo_hash[1] = 1
|
2021-03-07 21:34:50 +01:00
|
|
|
|
2021-03-07 22:00:10 +01:00
|
|
|
memoize(number, memo_hash)
|
2021-03-07 21:34:50 +01:00
|
|
|
end
|
|
|
|
|
2021-03-07 22:00:10 +01:00
|
|
|
def memoize(number, memo_hash)
|
|
|
|
return memo_hash[number] if memo_hash.keys.include? number
|
2021-03-07 21:34:50 +01:00
|
|
|
|
2021-03-07 22:00:10 +01:00
|
|
|
memo_hash[number] = memoize(number - 1, memo_hash) + memoize(number - 2, memo_hash)
|
2021-03-07 21:34:50 +01:00
|
|
|
|
2021-03-07 22:00:10 +01:00
|
|
|
memoize(number, memo_hash)
|
2021-03-07 21:15:05 +01:00
|
|
|
end
|
2021-03-07 21:34:50 +01:00
|
|
|
|
|
|
|
n = 2
|
2021-03-07 21:54:10 +01:00
|
|
|
fibonacci(n)
|
2021-03-07 21:34:50 +01:00
|
|
|
# Output: 1
|
|
|
|
# Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
|
|
|
|
|
|
|
|
n = 3
|
2021-03-07 21:54:10 +01:00
|
|
|
fibonacci(n)
|
2021-03-07 21:34:50 +01:00
|
|
|
# Output: 2
|
|
|
|
# Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
|
|
|
|
|
|
|
|
n = 4
|
2021-03-07 21:54:10 +01:00
|
|
|
fibonacci(n)
|
2021-03-07 21:34:50 +01:00
|
|
|
# Output: 3
|
|
|
|
# Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
|