☰ All problems

27. Generate Parentheses

Given an integer n, return every string made of exactly n opening brackets ( and n closing brackets ) that is well-formed.

A string is well-formed when every ) closes an earlier unmatched ( and nothing is left open at the end. Each string must appear once; the order of the list does not matter.

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

Constraints

  • 1 <= n <= 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