add more details to complexity analysis, add output

This commit is contained in:
Vitor Oliveira 2021-03-07 12:34:50 -08:00 committed by GitHub
parent 0a5ce13816
commit 2d2d1414d6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -7,18 +7,46 @@
# Given n, calculate F(n).
#
# Approach: Bottom-Up Approach using Memoization
# Approach: Top-Down Approach using Memoization
#
# Complexity Analysis:
#
# Time complexity: O(n)
# Space complexity: O(n)
# 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.
# Space complexity: O(n). The size of the stack in memory is
# proportionate to N.
#
def fib(n)
return n if n <= 1
def fibonacci(number, memo_hash = {})
if number == 0 || number == 1
return number
end
memo_hash[number] ||= fibonacci(number - 1, memo_hash) + fibonacci(number - 2, memo_hash)
cache = {}
cache[0] = 0
cache[1] = 1
memoize(n, cache)
end
def memoize(n, cache)
return cache[n] if cache.keys.include? n
cache[n] = memoize(n - 1, cache) + memoize(n - 2, cache)
memoize(n, cache)
end
n = 2
# Output: 1
# Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
puts(fib(n))
n = 3
# Output: 2
# Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
puts(fib(n))
n = 4
# Output: 3
# Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
puts(fib(n))