Generate All Valid Parentheses

Given an integer n, generate all strings with n matching parentheses. "matching" parentheses mean

  • there is equal number of opening and closing parentheses.
  • each opening parenthesis has matching closing parentheses.

For example, () is a valid string but )( is not a valid string because ) has no matching parenthesis before it and ( has no matching parenthesis after it.

Input

  • n: number of matching parentheses

Output

all valid strings with n matching parentheses

Examples

Example 1:

Input:

n = 2

Output: (()) ()()

Explanation:

There are two ways to create a string with 2 matching parentheses.

Example 2:

Input:

n = 3

Output: ((())) (()()) (())() ()(()) ()()()

Explanation:

There are 5 ways to create a string with 3 matching parentheses.

Try it yourself

Solution

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro