A parenthesis string is balanced if every ( has a matching ) that closes it and no prefix has more ) than (. Given an integer n, output every balanced string that uses exactly n pairs of parentheses (so each string has length 2n).
To make the answer unique, print the strings in lexicographic order. Compare characters by ASCII, where ( (code 40) is smaller than ) (code 41).
A single line containing the integer n.
Line 1: an integer M, the number of balanced strings (the n-th Catalan number).
The next M lines: one balanced string per line, in lexicographic order. When n = 0 the only balanced string is the empty string, printed as an empty line.
Three pairs
Input
3
Expected
5 ((())) (()()) (())() ()(()) ()()()
Explanation
Catalan(3) = 5 balanced strings. In lexicographic order ('(' before ')'): ((())), (()()) , (())(), ()(()), ()()(). (Shown without spaces on their own lines in the real output.)
One pair
Input
1
Expected
1 ()
Explanation
Catalan(1) = 1: the only balanced string with one pair is ().
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →