Generate Parentheses
Practice this coding question on Coding Gurukul.
Problem statement
A template editor uses parentheses to mark nested regions. Its test suite needs every valid nesting pattern with a specified number of region pairs. Your task Generate all distinct balanced parenthesis strings containing exactly n opening and n closing parentheses. Important details A prefix must never contain more closing than opening parentheses. Each completed string uses all n pairs. List the strings in ascending lexicographic order, with ( before ). Include each string once; different nesting structures are separate results. Worked example For n = 2, (()) nests one region inside another, while ()() places two regions side by side. These are the only two results, so print 2 and then those strings in that order.
Input format
One integer n.
Output format
Print the number of strings, followed by one string per line in lexicographic order.
Constraints
1 <= n <= 7.
Sample input
2
Sample output
2 (()) ()()
Sign in to run or submit a solution in C++, Java or Python.