100 XP

88. Balanced brackets, all of them

Advanced backtracking recursion

A string of brackets is balanced when every ( is closed by a later ) and no ) comes before its (: (())() is balanced, ())( isn't.

Write a function balanced(n) that takes a whole number n and returns every balanced string made of n pairs of brackets, that is n of ( and n of ):

  • Each string appears once.
  • The list is sorted in dictionary order, where ( comes before ). (That is Python's own order for these two characters, so sorted() gives it.)
  • With n = 0 the only balanced string is the empty one: [""].

Writing out every string of ( and ) and keeping the balanced ones works, but most of them are thrown away. It is better never to build a string that can't end up balanced.

Example 1

Inputn = 1
Output["()"]
ExplanationOne pair can only go one way.

Example 2

Inputn = 2
Output["(())", "()()"]
ExplanationOne pair inside the other, or side by side.

Example 3

Inputn = 0
Output[""]
ExplanationNo brackets: just the empty string.

Constraints

  • n is a whole number from 0 to 6.

Submit also runs 3 more tests you can't see.

Practises Recursion (lesson 20).

Code
def balanced(n):
    """List every balanced string of n bracket pairs.

    n: int, 0 or more
    Returns: list of str, each balanced string once, in
        dictionary order with "(" before ")"
    """
    # Write your code here
    pass