List every balanced string of n pairs of parentheses. Add an opener while you have one left, and a closer only when it has a match.
▼The problem
LeetCode 22 (Medium). Given n, return every well-formed string of n pairs of parentheses: each opener is closed, and no closer comes before its opener.
Example (LeetCode's): n = 3 → ["((()))", "(()())", "(())()", "()(())", "()()()"].
The solution
def generateParenthesis(n):
res, path = [], []
def build(opens, closes):
if len(path) == 2 * n:
res.append("".join(path))
return
if opens < n:
path.append("(")
build(opens + 1, closes)
path.pop()
if closes < opens:
path.append(")")
build(opens, closes + 1)
path.pop()
build(0, 0)
return resTranscript
Generate Parentheses. Given n, list every well-formed string of n pairs of parentheses. Well-formed means every opener gets closed, and no closer comes before its opener. This one works. This one doesn't: its third character closes nothing.
Say n is three. There are five answers, from fully nested to three pairs side by side. These counts are Catalan numbers: one, two, five, fourteen.
The naive way writes every string of six characters, two choices each: sixty-four strings. Then it checks each one, and throws away fifty-nine. That's four to the n strings. At n equals ten, it writes over a million to keep fewer than seventeen thousand.
Better: never build a bad string. Picture a roller coaster track, built left to right from the station. An opener lays a piece going up, a closer a piece going down. A good ride never dips below the station, and ends back on it. So keep two counters. Add an opener while you have one: open less than n. Add a closer only above the station: close less than open. Then every finished track is valid.
In code, a helper carries the two counts. When the path has two n pieces, record it. If an opener fits, append it, recurse, and pop it off. Then try a closer the same way.
Now build them all for n equals three. Up, up, up: no openers left, so down, down, down. That's the first ride, fully nested. Now backtrack: pull pieces off until a closer can go where an opener was, and climb again. Ride two. The rest follow the same way; a closer at the station is never laid. Five rides, all valid, nothing thrown away.
The answers grow with the Catalan numbers, a bit slower than four to the n, and each costs order n to copy. The recursion is two n deep, so the extra space is order n, plus the output.
Climb while you have pieces, come down only above the station, and keep every ride. That's Generate Parentheses.