☰ All problems

Generate Parentheses

The team behind a bracket-matching linter wants an exhaustive test suite: every properly balanced string that uses n pairs of round brackets, and nothing else.

Given n, return all strings of length 2n made of ( and ) in which every ) closes an earlier unmatched ( and no ( is still open at the end. Each string must appear exactly once, in any order.

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

Explanation: Two pairs can either nest or sit side by side.

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

Explanation: Four pairs can be balanced in 14 different ways.

Constraints

  • n is between 1 and 8.
💡 Hint 1

Build the string one character at a time. When is it legal to add (, and when is it legal to add )?

💡 Hint 2

You may add ( while fewer than n have been used, and ) only while it would close something (closed < opened).

💡 Hint 3

If you only ever make legal moves, every string of length 2n you reach is valid, so no filtering is needed.

/**
 * @param {number} n
 * @return {string[]}
 */
function generateParenthesis(n) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc