Need of Dynamic Programming in Python
1. Avoids Recomputing Subproblems (Overlapping Subproblems)
In recursion, the same subproblem may be solved multiple times. Dynamic Programming stores
results of subproblems (memoization or tabulation).
Example: Without DP (Recursive Fibonacci)
def fib(n): if n <= 1: return n return fib(n-1) + fib(n-2)
Example: With DP (Memoization)
def fib(n, memo={}): if n in memo: return memo[n] if n <= 1: return n
memo[n] = fib(n-1, memo) + fib(n-2, memo) return memo[n]
2. Solves Optimization Problems Efficiently
DP is used for problems like Knapsack, Longest Common Subsequence (LCS), and Matrix Chain
Multiplication.
3. Top-Down (Memoization) and Bottom-Up (Tabulation)
Approaches
Memoization uses recursion with caching. Tabulation uses iteration with arrays.
Example: Bottom-Up Fibonacci
def fib(n): dp = [0, 1] for i in range(2, n+1): dp.append(dp[i-1] +
dp[i-2]) return dp[n]
4. Makes Infeasible Problems Feasible
DP reduces time complexity from exponential to polynomial, making large problems solvable.
5. Used in Real-World Problems
Dynamic Programming is used in pathfinding (Dijkstra, Bellman-Ford), game theory, text similarity,
and resource allocation.
Summary
• Without DP: High time complexity, repeated work, may not give optimal solution
• With DP: Low time complexity, avoids repeated work, always gives optimal solution
• Used in problems like: Fibonacci, Knapsack, LCS, Matrix Chain Multiplication
• Approaches: Top-Down (Memoization), Bottom-Up (Tabulation)