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 {}{}{} {{{}}} {{}}{} {}{{}} {{}{}}
Push an opening parenthesis on top of the stack. In case of a closing bracket, check if the stack is empty. If not, pop in a closing parenthesis if the top of the stack contains the corresponding opening parenthesis. If the parentheses are valid, then the stack will be empty once the input string finishes.
Method Using StackCreate a stack. Traverse or iterate through the given string. Check for each character, if it is equal to '(' or any operator or operand, push it to the the stack. Else if it is equal to ')', pop the characters untill the open parenthesis of same kind is found.
The idea is to use stack. Iterate through the given expression and for each character in the expression, if the character is a open parenthesis '(' or any of the operators or operands, push it to the top of the stack.
Valid Parentheses solution in Java We iterate over the characters of the string, and for every iteration: if the current character is an opening bracket, we push it in the stack. if the character is a closing bracket, we pop the stack and check if the top of the stack contains its corresponding opening bracket or not.
This is a classic combinatorial problem that manifests itself in many different ways. These problems are essentially identical:
N
pairs of parentheses (i.e. this problem)N+1
factorsN+1
leavesHere's a simple recursive algorithm to solve this problem in Java:
public class Parenthesis { static void brackets(int openStock, int closeStock, String s) { if (openStock == 0 && closeStock == 0) { System.out.println(s); } if (openStock > 0) { brackets(openStock-1, closeStock+1, s + "<"); } if (closeStock > 0) { brackets(openStock, closeStock-1, s + ">"); } } public static void main(String[] args) { brackets(3, 0, ""); } }
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).
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 immutable String
of length N
is an O(N)
operation). Generally we optimize this by using a mutable StringBuilder
instead, but for this particular case we can also simply use a fixed-size char[]
and an index
variable.
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[]
and index
instead of String
, and recursing only to add open parentheses, adding close parentheses iteratively: (see also on ideone.com)
public class Parenthesis2 { public static void main(String[] args) { brackets(4); } static void brackets(final int N) { brackets(N, 0, 0, new char[N * 2]); } static void brackets(int openStock, int closeStock, int index, char[] arr) { while (closeStock >= 0) { if (openStock > 0) { arr[index] = '<'; brackets(openStock-1, closeStock+1, index+1, arr); } if (closeStock-- > 0) { arr[index++] = '>'; if (index == arr.length) { System.out.println(arr); } } } } }
The recursion logic is less obvious now, but the two optimization techniques are instructive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With