Back

Generate Parentheses

medium

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Test Cases

Copy an input into the main harness and Run to verify
Input
n = 3
Expected Output
["((()))","(()())","(())()","()(())","()()()"]
Input
n = 1
Expected Output
["()"]

Constraints

  • 1 <= n <= 8

Hints

Hint 1 — click to reveal

Build the string one character at a time instead of filtering all 2^(2n) strings.

Hint 2 — click to reveal

You may open a bracket while opens < n, and close one only while closes < opens.

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.