Generate Parentheses

Medium Backtracking AI round

n is a number of pairs of brackets. Each pair is an opening bracket ( and a closing bracket ).

A string of brackets is balanced when, read from the left, it never has more closing brackets than opening ones so far, and has as many of each at the end. Each closing bracket then closes the nearest opening bracket before it that is still open.

Return every balanced string made of exactly n pairs, each one once. The strings may come in any order.

Example 1

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

Two pairs sit side by side, ()(), or one inside the other, (()). Any other order of the four brackets, such as )(() or ())(, has a closing bracket with no open one before it to close.

Example 2

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

Constraints

  • 1 ≤ n ≤ 8
  • The largest answer, for n = 8, has 1,430 strings

More Backtracking

  • PermutationsAI round · Medium
  • SubsetsAI round · Medium
  • Combination SumMedium
  • Letter Combinations of a Phone NumberMedium
  • Word SearchMedium
All Backtracking problems