Dynamic Programming21 sections · 916 units
Open in Course

The General Pattern

State template

Most digit DP problems use this state: dp(pos,tight,started,...extra)dp(pos, tight, started, ...extra) pospos: current digit position (0 to length-1, left to right). tighttight: are we still bounded by NN? startedstarted: have we placed a non-zero digit yet? extraextra: problem-specific state (used digits, digit sum, remainder, etc.).

To compute dp, try each valid digit at pospos, updates the state, and recurses. Base case: when pospos equals the length, return 11 if valid, 00 otherwise.