title: Print all valid combinations of n-pairs of parentheses
body: <p>Left: As long as we haven’t used up all the left parentheses, we can always insert a left paren.
  Right: We can insert a right paren as long as it won’t lead to a syntax error. When will we get a syntax error  </p>
  
  <pre><code>public class parentheses {
  
      public static void printPar(int l, int r, char[] str, int count){  //Use recursion method to 
                                                                         // print the parentheses
          if(l == 0 &amp;&amp; r == 0){     //if there are no parentheses available, print them out  
              System.out.println(str); //Print out the parentheses
          }
  
          else{
              if(l &gt; 0){    // try a left paren, if there are some available
                  str[count] = '(';
                  printPar(l - 1, r, str, count + 1); //Recursion
              }
              if(r &gt; 0){   // try a right paren, if there are some available
                  str[count] = ')';
                  printPar(l, r - 1, str, count + 1);  //Recursion
              }
          }
      }
  
      public static void printPar(int count){
          char[] str = new char[count*2];   // Create a char array to store the parentheses
          printPar(count,count,str,0);      //call the printPar method, the parameters are the left,
                                              //the right parentheses, the array to store the 
                                              //parenthese, and the counter
      }
  
      public static void main(String[] args) {
          // TODO Auto-generated method stub
          printPar(2);  //
  
      }
  
  }
  </code></pre>
  
  <p>The result should be:</p>
  
  <pre><code>(())
  ()()
  </code></pre>
  
  <p>But what I get is:</p>
  
  <pre><code>(())
  ()()
  ())(
  )(()
  )()(
  ))((
  </code></pre>