Dynamic Programming Approach
Dynamic Programming Approach
def fib(n):
if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))
n = int(input("Enter n :"))
if n <= 0:
else:
print("Fibonacci sequence:")
for i in range(n):
Fib(5)
Fib(4) Fib(3)
Fib(2) Fib(1)
Fib(3) Fib(2)
Fib(1) Fib(0)
Fib(2) Fib(1) Fib(1) Fib(0)
Fib(1) Fib(0)
Even though the recursive approach is intuitive, it often leads to increased time complexity.
This is because the same subproblems are repeatedly calculated, resulting in redundant
computations and inefficient performance.
Definition:
Memoization solves the problem recursively while storing the results of subproblems
in a table (often a dictionary or array).
Process:
o When a subproblem is solved, its result is saved.
o If the same subproblem is encountered again, the solution is retrieved from the
table instead of being recalculated.
2. Tabulation (Bottom-Up Approach)
Definition:
Tabulation solves the problem iteratively by filling a table (usually an array) in a
bottom-up manner.
Process:
o Starts by solving the smallest subproblems.
o Uses their solutions to iteratively build solutions for larger subproblems.
Advantages:
o Eliminates recursion overhead.
o Suitable for problems where all subproblems need to be solved.
def fib(n):
return array
Using a bottom-up
Recursion frequently employs
methodology, dynamic
a top-down method in which
programming starts by
the primary problem is broken
resolving the smallest
down into more manageable
subproblems before moving
subproblems.
Approach on to the primary issue.
Memory Usage
Features Recursion Dynamic Programming