Parentheses Order (Small)
InterviewTime limit5sMemory limit512 MB
Print the k-th valid parentheses string of n pairs in lexicographic order for each test case, or report that it does not exist.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Combinatorics
- Solved
- No attempts yet
Problem
A parentheses string of length consists of opening brackets ( and closing brackets ).
A valid parentheses string is defined like this:
A string you can turn into the empty string by repeatedly erasing an adjacent () pair.
For example, (()) is valid. Erase the pair at positions 2 and 3 to get (), then erase that pair to get the empty string. )()( is not valid. Erasing the pair at positions 2 and 3 leaves )(, and nothing more can be erased.
Collect every valid parentheses string with opening and closing brackets, sort them in lexicographic order, and find the -th one. In this comparison ( comes before ).
For the valid parentheses strings in lexicographic order are:
((()))
(()())
(())()
()(())
()()()
Input
The first line has the number of test cases . Each of the next lines has two integers and separated by a space.
Output
For each test case print one line in the form Case #x: y. Here is the test case number starting from 1, and is the string that comes -th in lexicographic order among the valid parentheses strings with opening and closing brackets. If fewer than such strings exist, print Doesn't Exist! in place of .