PIXELBANKv9.1.0
Menu

Given n pairs of parentheses, generate all combinations of well-formed parentheses.

Output each combination on a separate line, sorted lexicographically.

Example:

Input:
3
Output:
((()))
(()())
(())()
()(())
()()()
Reasoning:
  • The problem starts with an input value of n = 3, representing the number of pairs of parentheses to generate.
  • The algorithm generates all possible combinations of well-formed parentheses, ensuring that each combination has n pairs of matching parentheses and that no closing parenthesis appears before its corresponding opening parenthesis.
  • The combinations are generated using a recursive approach, adding open and close parentheses at each step while maintaining a valid sequence: nopen≥nclosen_{open} \geq n_{close}.
  • The resulting combinations are then sorted lexicographically, resulting in the final output: ((())) (()()) (())() ()(()) ()()()

Constraints:

  • 1 <= n <= 8
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.