Problem Statement
Generate Parentheses
You are given a number n. It tells you how many pairs of parentheses you have. Your job is to build every possible string of those parentheses that is "well-formed". Well-formed means every open parenthesis "(" has a matching close ")" later, and you never close one that was not opened yet. The tool for this is backtracking. Backtracking is like exploring a maze: you walk down a path, and the moment you hit a dead end or a rule you cannot break, you back up and try a different turn. Here the rules are simple and they keep us out of dead ends before we even get there. (1) You can add an open "(" as long as you have not used all n of them. (2) You can add a close ")" only when there are more opens placed than closes, so there is something to close. Because we obey these two rules on every single step, every string we finish is automatically valid. We never have to go back and check the result.
Signals to notice
Brute force first
Generate all 2^(2n) strings of '(' and ')' and filter valid ones — exponential waste. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.
The key insight
Backtracking: track open and close counts. Add '(' if open < n, add ')' if close < open. When length = 2n, record the combination. — the Catalan number. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.
Trace it on n=2
start: cur='', open=0, close=0 -> open<n, add '('
cur='(', open=1, close=0 -> open<n add '('; close<open add ')' later
cur='((', open=2, close=0 -> open=n so skip '('; close<open add ')'
cur='(()', open=2, close=1 -> close<open add ')'
cur='(())', len=4=2n -> record '(())', return
back at cur='(': now close<open, add ')' -> cur='()', open=1, close=1
cur='()', open=1<n add '('; cur='()(', open=2, close=1 add ')' -> '()()'
cur='()()', len=4=2n -> record '()()'. Return result=['(())','()()']What must stay true
At any point, close count ≤ open count ≤ n. This constraint ensures every generated string is valid — you never close a bracket that wasn't opened. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.
Shape of the loop
backtrack(cur, open, close):
if len(cur) == 2*n: record(cur); return
if open < n: backtrack(cur+'(', open+1, close)
if close < open: backtrack(cur+')', open, close+1)
backtrack('', 0, 0)Pseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Adding ')' when close ≥ open — that creates an invalid string. The constraint close < open before adding ')' guarantees validity. The fix is usually to return to the meaning of each move, not just the steps themselves.