VFlash: Fast, Accurate Visual Planning via Flash Primitive Decoding
u_Unrolled
DSA for AI/ML · Module 08: Recursion and backtracking

Lesson 8.7 of 10 in this module Unrolled Pro

Generate Parentheses

All well-formed strings of n pairs of parentheses. From generating all 2^(2n) strings and filtering (most are invalid), to backtracking with two counters that only ever extends valid prefixes, so every leaf is an answer (the Catalan numbers). Then counting without listing, the same counters as a mask for constrained decoding so a model can only emit balanced output, sampling a uniformly random valid string by counting completions, and several bracket types.

about 10 min 5 Python examples 2 quick checks

Problem. Given n, generate all combinations of n pairs of parentheses that are well-formed (every ) closes an earlier unmatched ().

text
n = 1   →   ()
n = 2   →   (()) ()()
n = 3   →   ((())) (()()) (())() ()(()) ()()()

Lesson 6.2 checked whether a string is valid. Here we generate only valid strings, and the check becomes a rule that decides, at every step, which characters may come next.

ML context. That rule is exactly what constrained decoding does: when a model must produce valid JSON, a well-formed tool call or balanced code, the decoder keeps a small state (here, two counters; in general a stack or a grammar) and masks out every token that would make the output invalid. Change B builds that mask.


1. Step 1: Clarify

That's the preview. Modules 00–01 are free; this lesson is part of Unrolled Pro.
Staff AI & Pro Tier Lesson

Unlock "Generate Parentheses"

The foundations are free forever. Unrolled Pro unlocks the complete lesson, production architectures, and 55 battle-tested ML system design case studies.

Everything included with Pro:
All 234+ Deep-Dive Lessons across transformer internals, inference, RAG & agents
55 Staff-Level ML & System Design Case Studies with mathematical capacity estimates
AI Engineer Sheet & Exercises with worked solutions, self-checks, and code
100 Landmark Research Papers guided walkthroughs & progress tracking
14-Day Money-Back Guarantee — 100% full refund if you aren't satisfied
View Plans & Unlock All Lessons

From ₹167/mo (~$2/mo) · Cancel anytime · Instant activation

100% Risk-Free: 14-day no-questions-asked money-back guarantee