MediumBacktrackingRecursionString

1 approach, code in every language

Problem description

You are given a whole number n that represents how many pairs of round brackets are available. Your job is to produce every distinct arrangement of these brackets that is properly balanced, meaning each opening bracket is eventually closed and no closing bracket ever appears before a matching opening one.

Return the collection of all such well-formed strings. The relative ordering of the results is not important, but each valid arrangement must appear exactly once.

Example 1

Input: n = 2

Output: ["(())", "()()"]

With two pairs there are exactly two balanced layouts: a nested pair and two side-by-side pairs.

Example 2

Input: n = 1

Output: ["()"]

A single pair can only be written one way.

Constraints

  • 1 <= n <= 8
  • Every returned string has length exactly 2 * n
  • The count of valid results equals the nth Catalan number

After the pattern

Now solve one you haven't seen.

Ridge Walk Plans is our own problem on the technique behind Generate Parentheses: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free