8. Dynamic Programming
Dynamic Programming
Dynamic programming (DP) is an optimization technique used in algorithms to solve complex problems by breaking them down into simpler subproblems. It’s highly effective when subproblems overlap, allowing the reuse of previously computed solutions to avoid redundant calculations.
What is Dynamic Programming?
In dynamic programming, a complex problem is solved by dividing it into simpler subproblems, solving each only once, and storing their solutions in a table (usually an array). This stored data helps avoid recomputation, making dynamic programming efficient for problems with overlapping subproblems.
Characteristics of Dynamic Programming Problems
- Optimal Substructure: The optimal solution of the problem can be constructed from the optimal solutions of its subproblems.
- Overlapping Subproblems: Subproblems are reused multiple times, making it beneficial to store their results.
- Memoization: Storing the results of expensive function calls and returning the cached result when the same inputs occur again.
Tabulation Approach (Bottom-Up)
In the tabulation method, the solution is built incrementally by solving all subproblems first and using their results to solve the larger problem. This approach is referred to as bottom-up dynamic programming because it starts from the smallest subproblem and gradually works its way up.
Example: Fibonacci Sequence (Tabulation)
def fibonacci(n):
fib_table = [0] * (n + 1)
fib_table[1] = 1
for i in range(2, n + 1):
fib_table[i] = fib_table[i - 1] + fib_table[i - 2]
return fib_table[n]
print(fibonacci(10)) # Output: 55