Sunday 19 May 2013

Implement an algorithm to print all valid combination of n – pairs of parentheses properly opened and closed.

/*
      *  Example   n= 3.
      *  Output :  ((())) , (()()) , (())() , ()(()), ()()()
      *
      *  The problem can be solved by recursion. Select left or a right paren.
      *  If count(LeftParen) > 0 one can insert left paren.
      *  If count(RightParen) > count(LeftParen) i.e. no. of Left paren in an expression is greater than no. of right paren in the expression one can insert right parent.
      *
      *  1. Check for base case i.e. when no left or right paren are left all used up.
      *  2. If base case then print the string of parenthesis.
      *  3. If count of left parentheses > 0 then
      *        Insert Left parentheses in string str and decrement count of left parentheses by 1 and make recursive call.
      *  4. If count of right parentheses > count of left parentheses
      *        Insert right parentheses in string str and decrement count of right parentheses by 1 and make recursive call.
      *
*/ 
      void PrintParenthesis(int leftAvailable, int rightAvailable, string str)
      {
             if(leftAvailable == 0 && rightAvailable == 0)
             {
                   cout<<"n"<<str;
                   return;
             }
             if(leftAvailable >0)
                   PrintParenthesis(leftAvailable-1, rightAvailable, str+"(" );
             if(rightAvailable > leftAvailable)
                   PrintParenthesis(leftAvailable, rightAvailable-1, str+")" );    
      }

No comments:

Post a Comment