Computing the nth Fibonacci number using dynamic programming is pretty straightforward, you just need to store each Fibonacci number as you compute it and use previously computed numbers to compute the next ones.
Here is a simple Python implementation:
def fib(n):
F = [0, 1] + [0]*(n-1)
for i in range(2, n+1):
F[i] = F[i-1] + F[i-2]
return F[n]
This function creates an empty list βFβ of size βn+1β and initializes βF[0]β and βF[1]β to β0β and β1β respectively. After that, it computes each βF[i]β as βF[i-1] + F[i-2]β for βi = 2β to βnβ.
This approach allows it to calculate the nth Fibonacci number in O(n) time, which is much better than the naive recursive solution that takes O(2n) time.
We can also optimize this function by only keeping the last two previously computed Fibonacci numbers:
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a+b
return a
This version of the function computes the nth Fibonacci number in O(n) time and O(1) space.
If youβre interested in mathematical representations, hereβs a brief overview:
The Fibonacci sequence is formally defined by the recurrence relation:
βF(n) = F(n-1) + F(n-2)β
with βF(0) = 0β and βF(1) = 1β. Hence, the formula used in the dynamic programming-based implementations is βF[i] = F[i-1] + F[i-2]β for βi = 2β to βnβ.