0% found this document useful (0 votes)
34 views6 pages

DP Notes

Uploaded by

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

DP Notes

Uploaded by

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

Here’s a straight-up breakdown of the four pillars of mastering Dynamic

Programming. If you don’t get these, you’ll be just “copy-pasting” DP code, not
actually solving problems.

🧩 1. Identify Overlapping Subproblems


💡 What it means:
You're solving the same subproblem multiple times during recursion.

If brute-force recursion repeats the same calculations, you have overlapping


subproblems.

🧠 Intuition:
It’s like recalculating the same path in a maze again and again — unnecessary.

Example: Fibonacci

cpp
Copy
Edit
int fib(int n) {
if(n <= 1) return n;
return fib(n-1) + fib(n-2);
}
Calling fib(5) results in fib(3) being calculated twice, fib(2) three times… you
get the idea.

These are overlapping subproblems. Store them → save time → use memoization or
tabulation.

2. Recognize Optimal Substructure


💡 What it means:
The solution to a problem can be constructed from optimal solutions of its
subproblems.

If solving a big problem involves solving smaller, independent, and non-conflicting


subproblems — it has optimal substructure.

Example: Shortest path from node A to node B.

If the shortest path from A → B passes through C,


then shortest(A, B) = shortest(A, C) + shortest(C, B)

That’s optimal substructure.

🔁 If this doesn't hold, DP won’t work — you'd need something like greedy or
backtracking instead.

🔀 3. Know When to Use Memoization vs Tabulation


Feature Memoization (Top-down) Tabulation (Bottom-up)
Approach Recursive Iterative
Stack Usage Can cause stack overflow Safe, avoids recursion
Performance Slower due to function calls Faster, tight loops
Ease of Writing More intuitive More efficient
When to Use When state space is sparse When state space is dense

Example: Fibonacci

cpp
Copy
Edit
// Memoization
int fib(int n, vector<int>& dp) {
if(n <= 1) return n;
if(dp[n] != -1) return dp[n];
return dp[n] = fib(n-1, dp) + fib(n-2, dp);
}

// Tabulation
dp[0] = 0; dp[1] = 1;
for(int i = 2; i <= n; i++)
dp[i] = dp[i-1] + dp[i-2];
✅ Use memoization when you:

Have recursion in place

Are debugging logic

Only need partial state space

✅ Use tabulation when you:

Want high performance

Need bottom-up understanding

Are space/time optimizing

🧠 4. Learn State-Space Definition & Transition Formulation


💡 What it means:
You must define what each state represents and how it transitions from previous
states.

DP = Defining “what are you storing?” and “how does it evolve?”

🧠 Example 1: Climbing Stairs


dp[i] = number of ways to reach step i

cpp
Copy
Edit
dp[i] = dp[i-1] + dp[i-2]
Transition: You can reach step i either from step i-1 or i-2.

🧠 Example 2: 0/1 Knapsack


dp[i][w] = max value using first i items and total weight ≤ w

Transition:

cpp
Copy
Edit
dp[i][w] = max(
dp[i-1][w], // not take item i
dp[i-1][w - wt[i]] + val[i] // take item i
)
🔐 Summary (TL;DR)
Concept Core Question To Ask
Overlapping Subproblems "Am I solving the same thing again and again?"
Optimal Substructure "Can I build the answer from smaller answers?"
Memoization vs Tabulation "Do I want recursion or iteration?"
State & Transition "What does dp[i][j] mean? How do I get to it?"

Want me to convert this explanation into a mini PDF cheatsheet or flashcard format?
I can deliver that too.

🧾 DP Mastery Stages (With Problems)


📘 Stage 1: Base Foundation — 1D DP
🎯 Goal: Understand what DP is, learn the “states and transitions” mindset

🔹 Learn:
Recursion → Memoization → Tabulation → Space Optimization

How to define dp[i] and what it represents

Classic Fibonacci pattern

🧪 Problems:
✅ 70. Climbing Stairs

✅ 198. House Robber

✅ 746. Min Cost Climbing Stairs

✅ 509. Fibonacci Number

📙 Stage 2: DP on Subsequences
🎯 Goal: Learn problems with take or not-take decisions (0/1 choices)

🔹 Learn:
dp[i][j] means: using first i elements to achieve sum/cost j

Subset sum variants

🧪 Problems:
✅ Subset Sum

✅ 416. Partition Equal Subset Sum

✅ 494. Target Sum

✅ 1049. Last Stone Weight II

📗 Stage 3: Knapsack Variants


🎯 Goal: Learn bounded/unbounded choices

🔹 Learn:
0/1 Knapsack: pick once

Unbounded Knapsack: pick multiple times

Coin change patterns

🧪 Problems:
✅ 0/1 Knapsack
✅ 322. Coin Change

✅ 518. Coin Change II

✅ 139. Word Break

📕 Stage 4: DP on Strings
🎯 Goal: Master 2D DP with string transformations

🔹 Learn:
LCS (Longest Common Subsequence)

Edit distance

Palindromes

🧪 Problems:
✅ 1143. Longest Common Subsequence

✅ 72. Edit Distance

✅ 516. Longest Palindromic Subsequence

✅ 1312. Minimum Insertion Steps to Make a String Palindrome

📒 Stage 5: DP on Grids
🎯 Goal: Use DP with 2D paths — robot movement, min/max cost, obstacles

🔹 Learn:
State: dp[row][col]

Directions: right/down, up/left (careful with bounds)

🧪 Problems:
✅ 62. Unique Paths

✅ 63. Unique Paths II

✅ 64. Minimum Path Sum

✅ 741. Cherry Pickup

📓 Stage 6: LIS, Bitmasking & Digit DP


🎯 Goal: Handle complex transitions and optimization

🔹 Learn:
Longest Increasing Subsequence (LIS)

DP + Bitmask for combinatorics

Digit DP for number constraints

🧪 Problems:
✅ 300. Longest Increasing Subsequence

✅ 673. Number of Longest Increasing Subsequence

✅ 78. Subsets (bitmask warmup)


✅ 464. Can I Win (bitmask)

🔥 Stage 7: Advanced DP (State Compression, MCM, Trees)


🎯 Goal: Master structural DP and top-tier contest stuff

🔹 Learn:
Matrix Chain Multiplication (MCM)

Tree DP (postorder, rerooting)

State compression

🧪 Problems:
✅ 312. Burst Balloons

✅ 132. Palindrome Partitioning II

✅ 337. House Robber III

✅ 1937. Maximum Number of Points with Cost

no.. imeant for 1st designg flwo .. goingf i = 0 to n and base case at i== n or
going i = n to i = 0 ... and base case at i == 0 ..

ChatGPT said:
Ah, got it — you're asking about the two common design flows for recursive + DP
solutions, especially in problems like this one (partitioning/bitmask, etc.). Let’s
break them down.

✅ Two Flows of Designing a Recursive DP Solution


1. Forward DP: i = 0 to n (Base case at i == n)
🧠 Idea:
You're starting from the beginning of the array (i = 0) and making decisions as you
go forward until the end (i == n).

🎯 Use this when:

You're trying to build a solution from scratch, step by step.

The decisions depend on future elements.

Often used in problems like: "Partition array", "Count ways to reach the end",
"Subset sum", etc.

🧱 Skeleton:

cpp
Copy
Edit
int solve(int i) {
if (i == n) return base_case; // all elements handled

// try all possible decisions at position i


int ans = 0;
for (...) {
ans = max(ans, solve(i + 1));
}
return ans;
}
🧵 Thread of state: Position i, plus maybe some status (mask, sum, etc.)

2. Backward DP: i = n to 0 (Base case at i == 0)


🧠 Idea:
You're starting from the end (i = n) and solving the problem in reverse, building
the solution backwards.

🎯 Use this when:

You’re undoing actions or combining previously solved parts.

You're reconstructing from goal → base.

Works well in problems like: “Knapsack”, “Edit Distance”, some tree DP.

🧱 Skeleton:

cpp
Copy
Edit
int solve(int i) {
if (i == 0) return base_case; // nothing left

int ans = 0;
for (...) {
ans = max(ans, solve(i - 1));
}
return ans;
}
⚖️ Which One Should You Choose?
Factor Forward DP Backward DP
Natural in traversal ✅ Yes 🤔 Sometimes awkward
Easier for bitmask ✅ Often ✅ Sometimes
Useful when order matters ✅ Yes ⚠️ Be careful
Good for prefix building ✅ ❌
Good for suffix/rollback ❌ ✅

🤖 For Your Problem (Partition into A, B, C):


You are processing elements one-by-one → decision at each step: put in A / B / C.

✅ So, forward DP (i = 0 to n) is more natural here.

Want a clean forward DP with memoization + bitmask in C++ for this problem? I can
build it.

You might also like