Generate Parentheses

Backtracking, problem 6 of 8

Generate Parentheses

Medium

LC #22

backtrackingpruningstrings

Not attempted yet

Given n, return every well-formed string of n pairs of parentheses, in any order. Well-formed means every prefix has at least as many ( as ), and the totals match. So (() and )( are not allowed.

Example 1

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2

Input: n = 2
Output: ["(())","()()"]

Constraints

  • 1 ≤ n ≤ 8

Python

Loading draft…

Test results

5 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

2 examples, 3 hidden

Run examples, then submit all tests.