Possible Duplicate:
Solution to a recursive problem (code kata)
give an algorithm to find all valid permutation of parenthesis for given n
for eg :
for n=3, O/P should be
{}{}{}
{{{}}}
{{}}{}
{}{{}}
{{}{}}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Overview of the problem
This is a classic combinatorial problem that manifests itself in many different ways. These problems are essentially identical:
Npairs of parentheses (i.e. this problem)N+1factorsN+1leavesSee also
A straightforward recursive solution
Here’s a simple recursive algorithm to solve this problem in Java:
The above prints (as seen on ideone.com):
Essentially we keep track of how many open and close parentheses are “on stock” for us to use as we’re building the string recursively.
Note that if you swap the order of the recursion such that you try to add a close parenthesis before you try to add an open parenthesis, you simply get the same list of balanced parenthesis but in reverse order! (see on ideone.com).
An “optimized” variant
The above solution is very straightforward and instructive, but can be optimized further.
The most important optimization is in the string building aspect. Although it looks like a simple string concatenation on the surface, the above solution actually has a “hidden”
O(N^2)string building component (because concatenating one character to an immutableStringof lengthNis anO(N)operation). Generally we optimize this by using a mutableStringBuilderinstead, but for this particular case we can also simply use a fixed-sizechar[]and anindexvariable.We can also optimize by simplifying the recursion tree. Instead of recursing “both ways” as in the original solution, we can just recurse “one way”, and do the “other way” iteratively.
In the following, we’ve done both optimizations, using
char[]andindexinstead ofString, and recursing only to add open parentheses, adding close parentheses iteratively: (see also on ideone.com)The recursion logic is less obvious now, but the two optimization techniques are instructive.
Related questions