Every Well-Formed Bracket Sequence of a Given Length
Implement wellFormedBracketSequences
Given a count
n, produce every string of length 2n made of n opening and n closing brackets that is well-formed — every prefix has at least as many opens as closes, and the whole string balances out to zero by the end.
Trying every character independently at every position and checking validity only once a string is complete works, but wastes enormous effort on prefixes that were already unrecoverable — a string beginning with a closing bracket is built out to full length before that fact is even noticed. Tracking how many opens and closes have been placed so far, and only ever allowing a placement that keeps the running balance non-negative, means every partial string the search ever holds is one that could still become valid — nothing hopeless is ever built in the first place.
Example 1:
Input: n = 4
Output: ["(((())))","((()()))","((())())","((()))()","(()(()))","(()()())","(()())()","(())(())","(())()()","()((()))","()(()())","()(())()","()()(())","()()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Example 3:
Input: n = 0
Output: [""]
+ 2 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ n ≤ 8 - ●
Every returned string has exactly n opening and n closing brackets - ●
Results are returned sorted in ascending (lexicographic) order for a stable, checkable answer
n =
4