1782. Two-Kind Brackets
A code formatter checks text that uses two kinds of brackets, round () and square []. A string is balanced when every closing bracket matches the most recent opener that is still unmatched, and that opener has the same kind; every opener must eventually be closed.
Given n, return every balanced string of length 2 * n built only from the characters (, ), [ and ]. The result must list the strings in ascending ASCII order, where ( < ) < [ < ], with no duplicates. Build the strings with backtracking, keeping a stack of the kinds of currently open brackets and never opening a bracket that could not be closed in the remaining length. There are Catalan(n) * 2^n results, at most 224. Intended complexity: O(n * Catalan(n) * 2^n) time and O(n) extra space besides the output.
Example 1
- Input:
- n = 1
- Output:
- ["()","[]"]
- Explanation:
Only two strings of length 2 are balanced: () and [], listed in ASCII order.
Example 2
- Input:
- n = 2
- Output:
- ["(())","()()","()[]","([])","[()]","[[]]","[]()","[][]"]
- Explanation:
Eight strings of length 4 are balanced over both kinds, from (()) up to [[]] in ASCII order.
Example 3
- Input:
- n = 3
- Output:
- ["((()))","(()())","(())()","(())[]","(()[])","(([]))","()(())","()()()","()()[]","()([])","()[()]","()[[]]","()[]()","()[][]","([()])","([[]])","([]())","([])()","([])[]","([][])","[(())]","[()()]","[()[]]","[()]()","[()][]","[([])]","[[()]]","[[[]]]","[[]()]","[[][]]","[[]]()","[[]][]","[](())","[]()()","[]()[]","[]([])","[][()]","[][[]]","[][]()","[][][]"]
- Explanation:
There are 40 balanced strings of length 6; they are returned in ascending ASCII order.
Constraints
1 ≤ n ≤ 4 (at most 224 strings)
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n * Catalan(n) * 2^n)
- Space
- O(n)