Skip to contentKEEP THE CRAFTTHE SANCTUARY

Generate Balanced Parentheses

List every balanced string made of n pairs of parentheses.

The problem

Implement Solution.generateParenthesis(n). Return every balanced string that uses exactly n '(' and n ')' characters. A string is balanced when every ')' closes an earlier '(' that is still open. For example, n = 3 gives ["((()))", "(()())", "(())()", "()(())", "()()()"]. The result can be in any order. 1 <= n <= 8.

Starter code

class Solution:
    def generateParenthesis(self, n: int) -> list[str]:
        pass

Public examples

  1. n = 3gives["((()))", "(()())", "(())()", "()(())", "()()()"]
  2. n = 1gives["()"]
  3. n = 2gives["(())", "()()"]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.