Generate balanced parentheses
You get a whole number n. Return every string made of exactly n opening brackets ( and n closing brackets ) that is balanced: read left to right, every ) closes an earlier ( that is still open, and no ( is left open at the end.
So (()) and ()() are balanced. )( is not, because its ) has nothing to close, and (() is not, because one ( is never closed.
Return a list of strings that holds each balanced string exactly once, in any order.
n = 2Output["(())", "()()"]Two of each bracket can be arranged in 6 ways, and only these 2 are balanced. For example, ())( fails at its third character: a ) with nothing open.
n = 3Output["((()))", "(()())", "(())()", "()(())", "()()()"]5 of the 20 arrangements of three of each bracket are balanced.
n = 1Output["()"])( uses the same two brackets, but its ) comes before any (.
1 ≤ n ≤ 12
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.