Generate Parentheses

Medium#22open and close counts

You get a number n. Return every string of n "(" and n ")" that is balanced: read from the left, a ")" never comes when every "(" before it is already closed. Our example: n = 2 gives 2 strings, "(())" and "()()".

input
n: how many pairs of parentheses.
returns
Every string of n '(' and n ')' whose parentheses are balanced: no beginning of it closes more than it opens. Each string once, in any order.
constraints
  • 1 ≤ n ≤ 8
our 8 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number} n
 * @return {string[]}
 */
function generateParenthesis(n) {

}
Ctrl ↵
format
reset

saved in this browser

8 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more backtracking problems

Pattern “Backtracking” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.