Generate Parentheses

Medium
backtracking

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

A well-formed (valid) parentheses string has:

  1. Equal number of opening and closing parentheses
  2. At any prefix, the number of closing parentheses does not exceed opening ones

The backtracking approach: at each position, we can add '(' if we haven't used all n, or add ')' if the number of ')' is less than the number of '('.

The total number of valid combinations is the nth Catalan number: C(2n,n)/(n+1).

Example 1

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Explanation: There are 5 ways to arrange 3 pairs of valid parentheses.

Example 2

Input: n = 1
Output: ["()"]
Explanation: With 1 pair, there is only one valid arrangement.

Constraints

  • 1 <= n <= 8
Show Hints (4)
Hint 1: Track how many opening and closing parentheses you have used so far.
Hint 2: You can add "(" if open count < n.
Hint 3: You can add ")" only if close count < open count (to maintain validity).
Hint 4: When the string has 2n characters, you have a complete valid combination.
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?