You get a number n. Return every balanced string of n pairs of brackets, in any order.
Each string has n opening brackets ( and n closing brackets ).
A string is balanced when every ) closes a ( that comes before it. So, reading from the left, you never see more ) than (.
Example 1:
Input: n = 2 Output: ["(())","()()"] Explanation: The second pair goes inside the first pair, or right after it.
Example 2:
Input: n = 4
Output: ["(((())))","((()()))","((())())","((()))()","(()(()))",
"(()()())","(()())()","(())(())","(())()()","()((()))",
"()(()())","()(())()","()()(())","()()()()"]
Explanation: There are 14 balanced strings.
"(()))(()" is not balanced.
Its first five brackets hold two ( and three ).
Note: n is between 1 and 8.
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
