Get the FREE Ultimate OpenClaw Setup Guide →

dp-pattern-library

npx machina-cli add skill a5c-ai/babysitter/dp-pattern-library --openclaw
Files (1)
SKILL.md
8.7 KB

dp-pattern-library

A specialized skill for dynamic programming pattern recognition, matching problems to known DP patterns, generating template code, and providing optimization guidance for DP solutions.

Purpose

Assist with dynamic programming by:

  • Matching problems to 50+ classic DP patterns
  • Generating template code for matched patterns
  • Detecting problem variants (knapsack variants, LCS variants, etc.)
  • Providing state design recommendations
  • Suggesting optimization techniques

Capabilities

Core Features

  1. Pattern Recognition

    • Analyze problem statement for DP indicators
    • Match to known pattern categories
    • Identify problem variants and transformations
    • Suggest state representation
  2. Pattern Categories

    • Linear DP (1D array)
    • Grid/Matrix DP (2D paths)
    • String DP (LCS, edit distance)
    • Interval DP (ranges, parenthesization)
    • Tree DP (subtree problems)
    • Bitmask DP (subset enumeration)
    • Digit DP (number counting)
    • Knapsack variants
    • DP with state machine
  3. Code Generation

    • Template code for recognized patterns
    • Multiple language support (Python, C++, Java)
    • Comments explaining state and transitions
    • Space-optimized variants
  4. Optimization Guidance

    • Rolling array technique
    • Convex hull trick
    • Divide and conquer optimization
    • Monotonic queue/stack optimization
    • Knuth optimization

Pattern Library

Linear DP Patterns

PatternStateTransitionExample Problems
Fibonaccidp[i] = answer for position idp[i] = dp[i-1] + dp[i-2]Climbing Stairs, House Robber
Min/Max Pathdp[i] = best answer ending at idp[i] = opt(dp[j]) + cost(j,i)Minimum Path Sum
Countingdp[i] = ways to reach state idp[i] = sum(dp[j])Unique Paths, Decode Ways
LISdp[i] = LIS ending at idp[i] = max(dp[j]) + 1 where j < i, a[j] < a[i]Longest Increasing Subsequence

String DP Patterns

PatternStateExample Problems
Edit Distancedp[i][j] = distance for s1[0..i], s2[0..j]Edit Distance, One Edit Distance
LCSdp[i][j] = LCS of s1[0..i], s2[0..j]Longest Common Subsequence
Palindromedp[i][j] = is s[i..j] palindromeLongest Palindromic Substring
Regex Matchdp[i][j] = s[0..i] matches p[0..j]Regular Expression Matching

Knapsack Patterns

VariantStateTransition
0/1 Knapsackdp[i][w] = max value with items 0..i, capacity wdp[i][w] = max(dp[i-1][w], dp[i-1][w-wt[i]] + val[i])
Unboundeddp[w] = max value with capacity wdp[w] = max(dp[w], dp[w-wt[i]] + val[i])
Boundeddp[i][w] = max value with limited itemsUse binary representation or deque
Subset Sumdp[i][s] = can reach sum s with items 0..idp[i][s] = dp[i-1][s] or dp[i-1][s-a[i]]

Grid DP Patterns

PatternStateExample Problems
Path Countdp[i][j] = ways to reach (i,j)Unique Paths, Unique Paths II
Path Min/Maxdp[i][j] = best path to (i,j)Minimum Path Sum
Multi-pathdp[i][j][k][l] = two paths simultaneouslyCherry Pickup

Interval DP Patterns

PatternStateExample Problems
MCMdp[i][j] = cost for range [i,j]Matrix Chain Multiplication
Burstdp[i][j] = max coins from balloons[i..j]Burst Balloons
Mergedp[i][j] = cost to merge range [i,j]Minimum Cost to Merge Stones

Tree DP Patterns

PatternStateExample Problems
Subtreedp[v] = answer for subtree rooted at vBinary Tree Maximum Path Sum
Rerootingdp[v] = answer when v is rootSum of Distances in Tree
Parent-Childdp[v][0/1] = answer with constraintHouse Robber III

Bitmask DP Patterns

PatternStateExample Problems
TSPdp[mask][last] = min cost visiting mask cities ending at lastTraveling Salesman Problem
Assignmentdp[mask] = min cost assigning tasks to subsetTask Assignment
SOSdp[mask] = sum over subsetsSubset Sum over Subsets

Usage

Pattern Matching

# Match problem to DP pattern
dp-pattern-library match --problem "Given an array of integers, find the longest increasing subsequence"

# Output:
# Pattern: Linear DP - Longest Increasing Subsequence (LIS)
# State: dp[i] = length of LIS ending at index i
# Transition: dp[i] = max(dp[j] + 1) for all j < i where arr[j] < arr[i]
# Time: O(n^2) naive, O(n log n) with binary search
# Space: O(n)

Template Generation

# Generate template code
dp-pattern-library template --pattern "lis" --language python

# Output:
def lengthOfLIS(nums):
    if not nums:
        return 0

    n = len(nums)
    # dp[i] = length of LIS ending at index i
    dp = [1] * n

    for i in range(1, n):
        for j in range(i):
            if nums[j] < nums[i]:
                dp[i] = max(dp[i], dp[j] + 1)

    return max(dp)

Optimization Suggestions

# Get optimization recommendations
dp-pattern-library optimize --pattern "lis"

# Output:
# Current: O(n^2) time, O(n) space
# Optimizations:
# 1. Binary Search: O(n log n) time
#    - Maintain sorted list of smallest tail elements
#    - Binary search for insertion point
# 2. Segment Tree: O(n log n) time
#    - For coordinate compression + range max query

Output Schema

{
  "match": {
    "pattern": "Linear DP - LIS",
    "confidence": 0.95,
    "category": "linear",
    "variants": ["LIS", "LDS", "LNDS"]
  },
  "state": {
    "description": "dp[i] = length of LIS ending at index i",
    "dimensions": 1,
    "meaning": "LIS length ending at position i"
  },
  "transition": {
    "formula": "dp[i] = max(dp[j] + 1) for j < i, arr[j] < arr[i]",
    "baseCase": "dp[i] = 1 for all i",
    "order": "left to right"
  },
  "complexity": {
    "time": "O(n^2)",
    "space": "O(n)",
    "optimized": {
      "time": "O(n log n)",
      "technique": "binary search on patience sort"
    }
  },
  "template": {
    "python": "...",
    "cpp": "...",
    "java": "..."
  },
  "similarProblems": [
    "Longest Increasing Subsequence",
    "Number of Longest Increasing Subsequence",
    "Russian Doll Envelopes",
    "Maximum Length of Pair Chain"
  ]
}

Integration with Processes

This skill enhances:

  • dp-pattern-matching - Core pattern matching workflow
  • dp-state-optimization - State space optimization
  • dp-transition-derivation - Deriving transitions
  • leetcode-problem-solving - DP problem identification
  • classic-dp-library - Building a personal DP library

Pattern Recognition Indicators

IndicatorLikely Pattern
"maximum/minimum" + "subarray/subsequence"Linear DP
"number of ways"Counting DP
"can reach/achieve"Boolean DP
"edit/transform string"String DP
"merge/combine intervals"Interval DP
"tree/subtree"Tree DP
"select subset" + small nBitmask DP
"count numbers with property"Digit DP
"items + capacity"Knapsack

References

Error Handling

ErrorCauseResolution
NO_PATTERN_MATCHProblem doesn't fit known patternsConsider greedy or other approaches
AMBIGUOUS_MATCHMultiple patterns could applyProvide more problem details
COMPLEX_STATEState too complex for templatesManual state design needed

Best Practices

  1. Start with brute force - Understand recurrence before optimizing
  2. Draw state diagram - Visualize transitions
  3. Verify base cases - Most DP bugs are in base cases
  4. Check state uniqueness - Each state should be uniquely defined
  5. Consider space optimization - Often can reduce dimension
  6. Test with small inputs - Trace through by hand

Source

git clone https://github.com/a5c-ai/babysitter/blob/main/plugins/babysitter/skills/babysit/process/specializations/algorithms-optimization/skills/dp-pattern-library/SKILL.mdView on GitHub

Overview

This skill analyzes DP problem statements, maps them to 50+ classic DP patterns, and generates ready-to-use templates in Python, C++, or Java. It also detects problem variants (knapsack, LCS, etc.) and provides state design guidance and optimization tips to speed up DP solutions.

How This Skill Works

The tool scans problem indicators, classifies the DP category (Linear, Grid, String, Interval, Tree, Bitmask, Digit, Knapsack, or state-machine DP), and identifies variants. It then outputs a template code with explanatory comments and optional space-optimized versions across supported languages.

When to Use It

  • You’re starting a DP problem and aren’t sure which pattern fits.
  • Working on a 1D linear DP like Fibonacci, LIS, or counting paths.
  • Facing a grid/matrix DP task (path count, min/max path).
  • Dealing with string DP problems (LCS, Edit Distance, Palindrome, Regex Match).
  • You want to map to a known variant (Knapsack, Bitmask, Digit DP) and generate cross-language templates.

Quick Start

  1. Step 1: Provide the problem statement and your preferred language (Python, C++, or Java).
  2. Step 2: Let the tool map the problem to a DP pattern and detect any variants.
  3. Step 3: Review and implement the generated template, then adapt states and transitions.

Best Practices

  • Identify the primary DP category early (Linear, Grid, String, Interval, Tree, Knapsack, etc.).
  • Detect problem variants and needed state design (indices, masks, or dimensions).
  • Use the generated template as a starting point and customize states and transitions.
  • Prefer space/time optimizations (rolling arrays, DnC optimization, monotonic structures) when applicable.
  • Validate with small, edge-case tests to ensure correctness and stability.

Example Use Cases

  • Climbing Stairs or Fibonacci: simple linear DP pattern.
  • Minimum Path Sum: grid path DP with 2D state.
  • Unique Paths: counting DP in a grid with combinatorial transitions.
  • Longest Increasing Subsequence: LIS pattern in a linear DP.
  • Edit Distance or LCS: classic string DP problems with 2D states.

Frequently Asked Questions

Add this skill to your agents
Sponsor this space

Reach thousands of developers