Balanced Parenthesis
Problem Description:
Solutions:
Solution is simple.
For given 15 > n > 0, print all balanced parenthesis
eg:
For n = 1
()
n = 2
()()
(())
n=3
((()))
(()())
(())()
()(())
()()()
Solutions:
Solution is simple.
- Start with empty string
- Add only valid parenthesis at the end
- And continue until you reach to the length
Code:
public class BalancedParenthesis {
public void printParenthesis(int n) {
print("", n, 0, 0);
}
private void print(String strSoFar, int n, int opc, int cpc) {
if(opc == n && cpc == n) {
System.out.println(strSoFar);
}
if(opc < n) {
print(strSoFar + "(", n, opc + 1, cpc);
}
if(cpc < opc) {
print(strSoFar + ")", n, opc, cpc + 1);
}
}
public static void main(String[] agrs) {
BalancedParenthesis bp = new BalancedParenthesis();
bp.printParenthesis(3);
}
}
Comments
Post a Comment