Skip to content

Instantly share code, notes, and snippets.

@dongr0510
Created September 12, 2020 00:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dongr0510/fe7e28368424cbdc539e245159ed8665 to your computer and use it in GitHub Desktop.
Save dongr0510/fe7e28368424cbdc539e245159ed8665 to your computer and use it in GitHub Desktop.
# Basic Solution
def calFib(n):
if n < 2:
return n
return calFib(n-1) + calFib(n-2)
# Top-down DP with Memorization
def calculateFibonacci(n):
memoize = [-1 for x in range(n+1)]
return calculateFibonacciRecur(memoize, n)
def calculateFibonacciRecur(memoize, n):
if n < 2:
return n
# if we have already solved this subproblem, simply return the result from the cache
if memoize[n] >= 0:
return memoize[n]
memoize[n] = calculateFibonacciRecur(
memoize, n - 1) + calculateFibonacciRecur(memoize, n - 2)
return memoize[n]
# Bottom-up DP
def calculateFibonacci(n):
if n < 2:
return n
dp = [0, 1]
for i in range(2, n + 1):
dp.append(dp[i - 1] + dp[i - 2])
return dp[n]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment