Created
September 12, 2020 00:27
-
-
Save dongr0510/fe7e28368424cbdc539e245159ed8665 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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