/22. Generate Parentheses

22. Generate Parentheses

Medium
Strings78.4% acceptance

Given an integer pair_count, return a list of all possible strings representing valid sequences of pair_count pairs of parentheses. Each sequence must be well-formed, meaning every opening parenthesis ( has a corresponding closing parenthesis ) and parentheses are properly nested.

Example 1

Input: 2

Output: [(()), ()()]

Explanation: There are two valid sequences for 2 pairs: (()) and ()().

Example 2

Input: 4

Output: [(((()))), ((()())), ((())()), ((()))(), (()(())), (()()()), (()())(), (())(()), (())()(), ()((())), ()(()()), ()(())(), ()()(()), ()()()()]

Explanation: All valid sequences for 4 pairs.

Constraints

  • 1 <= pair_count <= 8
Python (current runtime)

Case 1

Input: 3

Expected: ['((()))', '(()())', '(())()', '()(())', '()()()']

Case 2

Input: 5

Expected: ['((((()))))', '(((()())))', '(((())()))', '(((()))())', '(((())))()', '((()(())))', '((()()()))', '((()())())', '((()()))()', '((())(()))', '((())()())', '((())())()', '((()))(())', '((()))()()', '(()((())))', '(()(()()))', '(()(())())', '(()(()))()', '(()()(()))', '(()()()())', '(()()())()', '(()())(())', '(()())()()', '(())((()))', '(())(()())', '(())(())())', '(())(())()', '(())()(())', '(())()()()', '()(((())))', '()((()()))', '()((())())', '()((()))()', '()(()(()))', '()(()()())', '()(()())()', '()(())(())', '()(())()()', '()()((()))', '()()(()())', '()()(())()', '()()()(())', '()()()()()']

Case 3

Input: 1

Expected: ['()']