All problems

Problem 284

Kth Valid Parentheses String

Medium · 20 pts · String, Backtracking, Recursion

Problem

A string of N pairs of parentheses is valid if every '(' is closed by a later ')' and no ')' appears without a matching '(' before it. List all valid strings of N pairs in lexicographic order, where '(' comes before ')'. Print the K-th string of the list, or -1 if the list has fewer than K strings. Generate the strings with backtracking, always trying '(' before ')': add '(' while fewer than N have been used, and add ')' while there are unmatched '(' characters. This produces the strings already in lexicographic order, so you can stop at the K-th one.

Input

Two integers N and K.

Output

Print the K-th valid string, or -1.

Constraints

1 <= N <= 10; 1 <= K <= 100000

Example input

3 2

Example output

(()())

Explanation

For N = 3 the valid strings in order are ((())), (()()), (())(), ()(()) and ()()(). The 2nd of these is (()()).

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: N-Queens Count Next: All Permutations