mediumBacktrackingPure DSA~25 min
Generate All Well-Formed Bracket Layouts
A templating engine needs every valid way to nest n pairs of brackets — useful for enumerating balanced wrapper structures. Produce all well-formed combinations.
Problem
Given an integer n, return all distinct strings of n pairs of parentheses that are well-formed (every opening bracket is properly closed and never closes before it opens).
Input
A single integer n.
Output
A list of all valid parenthesis strings of length 2n (any order).
Constraints
- 1 ≤ n ≤ 8
Examples
Example 1
Input
n=3
Output
["((()))","(()())","(())()","()(())","()()()"]
All five well-formed arrangements of 3 pairs.
Example 2
Input
n=1
Output
["()"]
Only one valid arrangement for a single pair.