Generate Parentheses
Generate Parentheses is LeetCode 22 (Medium). Given n, return every string of n opening and n closing brackets that is well-formed: each ( is closed by a later ), and no ) appears before an open bracket it can close. The strings can be returned in any order.
nis at most 8, which gives 1,430 strings, so listing all of them is the job.
- 1 <= n <= 8
Intuition
Build the string one bracket at a time and only add a bracket that can still lead to a valid string. Two counts decide that:
- Open:
(is allowed while fewer thannhave been used. - Close:
)is allowed only while there are more opens than closes, so some open bracket is waiting for it.
A prefix that obeys both rules can always be finished, by closing every open bracket. So the search never walks into a dead end, and every string it completes at length 2n is a valid answer.
"List every arrangement that satisfies a rule" with tiny input is backtracking. If the rule can be checked on a prefix, check it before adding each character instead of filtering finished strings.
Approach
Before reading on, write the condition for adding ( and the condition for adding ) using only two counts: opens used and closes used. Then check that a prefix following both rules can always be completed.
Track the brackets used so far
Keep the current string as a list path, plus opened and closed, the counts of each bracket in it. Start with an empty path and both counts at 0.
Add an open bracket while any are left
If opened < n, append (, recurse with opened + 1, then pop it off. Popping restores the path, so the same list can try the next choice at this position.
Add a close bracket only if one is waiting
If closed < opened, append ), recurse with closed + 1, then pop. This keeps every prefix with at least as many opens as closes, which is exactly what well-formed means.
Record the string at full length
When path has 2n characters, both counts equal n, so join it and add it to the result. No final check is needed, because the two rules were enforced at every step.
Why each answer appears exactly once
A valid string is a list of choices that the two rules allow, so the search follows that exact path and records it. Two different paths differ at some position, so the same string is never recorded twice.
Code in Python, C++ and Java
( to get (. Opens are left and 1 bracket is waiting to be closed, so both moves stay possible; the open one is tried first.( to get ((. Opens are left and 2 brackets are waiting to be closed, so both moves stay possible; the open one is tried first.( to get (((. All 3 opens are used, so the path can only go down from here.) to get (((), coming back from the last branch to try the other move. No opens are left, so only closes can follow.) to get ((()), coming back from the last branch to try the other move. No opens are left, so only closes can follow.((())) has 6 brackets, all 3 opens and 3 closes. Every bracket was added under the two rules, so it is well-formed without any check. Record it, then go back to the last place with an untried choice.) to get ((), coming back from the last branch to try the other move. Opens are left and a bracket is still waiting, so both moves are possible.( to get (()(. All 3 opens are used, so the path can only go down from here.) to get (()(), coming back from the last branch to try the other move. No opens are left, so only closes can follow.(()()) has 6 brackets, all 3 opens and 3 closes. Every bracket was added under the two rules, so it is well-formed without any check. Record it, then go back to the last place with an untried choice.) to get (()), coming back from the last branch to try the other move. Every open bracket is now closed, so a close is not allowed; only an open bracket can come next.( to get (())(. All 3 opens are used, so the path can only go down from here.(())() has 6 brackets, all 3 opens and 3 closes. Every bracket was added under the two rules, so it is well-formed without any check. Record it, then go back to the last place with an untried choice.) to get (), coming back from the last branch to try the other move. Every open bracket is now closed, so a close is not allowed; only an open bracket can come next.( to get ()(. Opens are left and 1 bracket is waiting to be closed, so both moves stay possible; the open one is tried first.( to get ()((. All 3 opens are used, so the path can only go down from here.) to get ()((), coming back from the last branch to try the other move. No opens are left, so only closes can follow.()(()) has 6 brackets, all 3 opens and 3 closes. Every bracket was added under the two rules, so it is well-formed without any check. Record it, then go back to the last place with an untried choice.) to get ()(), coming back from the last branch to try the other move. Every open bracket is now closed, so a close is not allowed; only an open bracket can come next.( to get ()()(. All 3 opens are used, so the path can only go down from here.()()() has 6 brackets, all 3 opens and 3 closes. Every bracket was added under the two rules, so it is well-formed without any check. Record it, then go back to the last place with an untried choice.( is always tried first.( to get (. Opens are left and 1 bracket is waiting to be closed, so both moves stay possible; the open one is tried first.( to get ((. All 2 opens are used, so the path can only go down from here.) to get ((), coming back from the last branch to try the other move. No opens are left, so only closes can follow.(()) has 4 brackets, all 2 opens and 2 closes. Every bracket was added under the two rules, so it is well-formed without any check. Record it, then go back to the last place with an untried choice.) to get (), coming back from the last branch to try the other move. Every open bracket is now closed, so a close is not allowed; only an open bracket can come next.( to get ()(. All 2 opens are used, so the path can only go down from here.()() has 4 brackets, all 2 opens and 2 closes. Every bracket was added under the two rules, so it is well-formed without any check. Record it, then go back to the last place with an untried choice.( is always tried first.( to get (. All 1 opens are used, so the path can only go down from here.() has 2 brackets, all 1 opens and 1 closes. Every bracket was added under the two rules, so it is well-formed without any check. Record it, then go back to the last place with an untried choice.Common pitfalls
Allowing a close bracket whenever closes are left
if closed < n:
if closed < opened:
Having closes left is not enough; an open bracket must be waiting. With the wrong test, n = 1 returns ["()", ")("], and n = 2 returns six strings, four of them invalid.
Appending without popping
path.append("(")
build(opened + 1, closed)path.append("(")
build(opened + 1, closed)
path.pop()The shared path keeps the brackets from the branch that just finished, so the next branch starts from a string that is too long. For n = 2 the result is only ["(())"]; "()()" is lost because the path never shrinks back.
Complexity
path, both 2n, not counting the output.Generate Parentheses FAQ
How many strings are there for a given n?
The nth Catalan number, (2n)! / ((n + 1)! · n!). For n = 1 to 8 that is 1, 2, 5, 14, 42, 132, 429 and 1,430.
Why not build every bracket string and keep the valid ones?
It works, but there are 2²ⁿ strings of length 2n: 65,536 when n = 8, of which only 1,430 are valid. Checking each one costs O(n) too. The two rules stop an invalid string at its first bad bracket, so only the 1,430 valid strings are ever completed.
Can the answers be built from smaller ones?
Yes. Every valid string starts with (, and that bracket's matching ) splits it into ( + A + ) + B, where A has k pairs and B has n − 1 − k. Combining the stored answers for every k builds the list for n from the lists for smaller sizes. It is a dynamic-programming version with the same output, but it keeps every smaller list in memory.