0% found this document useful (0 votes)
2 views2 pages

Need of Dynamic Programming in Python

Uploaded by

chandramjan4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Need of Dynamic Programming in Python

Uploaded by

chandramjan4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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)

You might also like