problems / 125

Balanced Brackets Within a Depth Limit

easy backtracking strings 1000 ms · 256 MB

Balanced Brackets Within a Depth Limit

A string of n opening brackets ( and n closing brackets ) is balanced if, reading it from left to right, the number of ) read so far never exceeds the number of ( read so far.

The depth after a prefix of the string is the number of ( in the prefix minus the number of ) in it. The nesting depth of a balanced string is the largest depth over all of its prefixes. For example, (())() has nesting depth 2 and ()()() has nesting depth 1.

Given n and D, list every balanced string of n bracket pairs whose nesting depth is at most D.

Input

A single line contains two integers n and D (1 ≤ D ≤ n ≤ 20).

It is guaranteed that there are at most 10^5 strings to list.

Output

On the first line print the number of strings k. Then print the k strings, one per line, in lexicographic order, where ( is considered smaller than ).

Notes

In the first example, of the five balanced strings with three pairs, only ((())) goes three levels deep, so the other four are listed.

In the second example, a depth limit of 1 leaves only one choice: every ( must be closed immediately.

Example 1

Input

3 2

Output

4
(()())
(())()
()(())
()()()

Example 2

Input

4 1

Output

1
()()()()

Hints · reveal one at a time if you're stuck

Hint 1

Build each string one character at a time and try every choice, with the choice order chosen so the output comes out lexicographically. What two running quantities tell you whether a choice is still legal?

Hint 2

Track how many opening brackets you have used and the current depth. Prune a branch as soon as the depth would exceed the limit, not after the whole string is built, and make sure every surviving prefix can still be completed.

report an issue Prefer your own editor? sooks prep 125 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.