Understanding Generate Parentheses
Generate every distinct balanced string containing n pairs of parentheses. Results may be returned in any order.
How it works
Reject invalid prefixes while building them, instead of generating and checking every possible string.
Add an opening bracket while open < n; add a closing bracket only while close < open. Save a string when its length is 2n.
Try an example
Input: n = 3
Output: ["((()))", "(()())", "(())()", "()(())", "()()()"]
Every prefix has at least as many opening brackets as closing brackets.
Constraints
- 0 ≤ n ≤ 5 for bounded visualizations.
- For n = 0, return an array containing the empty string.
- Do not return duplicate strings.
Use the simulator
Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.
Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.