Start learning free

LESSON 406 OF 671 · BACKTRACKING

Generate Parentheses

Practice O(2^n)

You get a number n. Return every balanced string of n pairs of brackets, in any order.

Each string has n opening brackets ( and n closing brackets ).

A string is balanced when every ) closes a ( that comes before it. So, reading from the left, you never see more ) than (.


Example 1:

Input: n = 2
Output: ["(())","()()"]
Explanation: The second pair goes inside the first pair, or right after it.

Example 2:

Input: n = 4
Output: ["(((())))","((()()))","((())())","((()))()","(()(()))",
         "(()()())","(()())()","(())(())","(())()()","()((()))",
         "()(()())","()(())()","()()(())","()()()()"]
Explanation: There are 14 balanced strings.
"(()))(()" is not balanced.
Its first five brackets hold two ( and three ).

Note: n is between 1 and 8.


STEP 1 OF 10
    Ctrl + Enter to check