Balanced Parenthesis

Problem Description:


  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

Popular posts from this blog

Scala Learning: Finding Square Root

Deleting a hidden user in MAC

Problem Solving: Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node