Understand the Problem and Constraints:
n stairs with 1 or 2 steps.Identify the DP Pattern:
Define the State:
dp[i] (1D), dp[i][j] (2D), or dp[i][j][k] (3D), where each dimension captures a parameter like position, capacity, or condition.dp[i][w] represents the maximum value for the first i items with weight capacity w.Formulate the Recurrence Relation:
dp[i] = dp[i-1] + dp[i-2] (ways to climb i stairs = ways to climb i-1 + ways to climb i-2).Determine Base Cases:
dp[0], dp[1], or empty inputs).dp[i][0] = 0 and dp[0][j] = 0 (no common subsequence with empty strings).Choose the Approach: Memoization or Tabulation:
Design the Algorithm:
Write pseudocode or a plan:
Example: For 0/1 Knapsack:
Initialize dp[i][w] = 0 for all i, w
Set base cases: dp[0][w] = 0, dp[i][0] = 0
For each item i:
For each weight w:
If weight[i-1] <= w:
dp[i][w] = max(dp[i-1][w], dp[i-1][w-weight[i-1]] + value[i-1])
Else:
dp[i][w] = dp[i-1][w]
Return dp[n][W]
Optimize Space and Time:
dp[i-1] and dp[i-2], reducing space from O(n) to O(1).Implement the Solution:
Test and Debug:
n = 1, n = 2).nums = [1,3,2] to ensure dp[i] captures the correct length.Formulate the Answer:
Thinking through a DP solution involves breaking down the problem, recognizing patterns, and iteratively refining the approach. Here’s how to approach it:
j using the first i coins?”dp[i] = dp[i-1] + dp[i-2]).dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + cost).n = 3: Ways = ways(2) + ways(1) = 2 + 1 = 3.dp[i-1] is reused in multiple calculations).word1 = "cat", word2 = "cut" to see how operations (insert, delete, replace) build the solution.