Generate Parentheses
MediumStack
Given an integer n, return all strings of length 2 * n made of n opening ( and n closing ) parentheses that are balanced.
A string is balanced when, reading left to right, the number of ) never exceeds the number of ( seen so far, and the two counts are equal at the end.
Each balanced string must appear exactly once. The strings may be returned in any order.
Example 1
- Input:
- n = 2
- Output:
- ["(())", "()()"]
- Explanation
- Of the six ways to arrange two
(and two), only the nested form and the side-by-side form are balanced. Strings like())(fail because a)arrives before its matching(.
Example 2
- Input:
- n = 4
- Output:
- ["(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()"]
- Explanation
- There are 14 balanced strings with four pairs. They can be listed in any order.
Constraints
- 1 ≤
n≤ 8