Problem 529773 · medium · Phase 05 Advanced Algorithms & Graphs

Well-Formed Bracket Strings

backtracking · strings · counting invariants

A formatter needs every well-formed string made of n opening brackets [ and n closing brackets ]. A string is well-formed when reading it left to right the number of ] never exceeds the number of [, and both counts finish equal. Return all such strings in any order.

Examples

Input:  n = 2
Output: ["[][]", "[[]]"]

Input:  n = 1
Output: ["[]"]

Input:  n = 0
Output: [""]

Constraints

  • 0 <= n <= 7 (at most 429 strings)

Goals

  • Generate strings under an invariant: never close more than you have opened
  • Track opened and closed counts as recursion parameters
Starting Python…