Enumerating Brackets
InterviewTime limit2sMemory limit512 MB
Given N and M, print the M-th balanced bracket sequence of length N in lexicographic order, where '(' is smaller than ')'.
- Level
Medium6 of 10
- Topics
- Combinatorics, Dynamic programming, Greedy, Implementation
- Solved
- No attempts yet
Problem
A balanced bracket sequence is a string made only of the characters ( and ) in which every opening bracket has a matching closing bracket, and every closing bracket has a matching opening bracket. For example, (())() is a balanced bracket sequence, while (())(() and ())(() are not.
Let and be two bracket sequences of the same length. We say that is lexicographically smaller than , written , when both of the following hold:
- and differ in at least one position.
- At the leftmost position where and differ, has a
(and has a).
For example, , because the two strings first differ at the second position from the left, where the first string has a ( and the second has a ).
For a fixed length , the relation orders all balanced bracket sequences of length . For the order is:
((()))(()())(())()()(())()()()
Given and a positive integer , find the -th balanced bracket sequence of length in this order.
Input
The first line contains an even integer () and a positive integer , separated by a space. is at most , and is also at most the number of balanced bracket sequences of length .
Output
Print the -th balanced bracket sequence of length in the order described above.