Tuesday, August 23, 2016

Leetcode 22. Generate Parentheses

 public class Solution {  
   public IList<string> GenerateParenthesis(int n) {  
     List<string> ret = new List<string>();  
     string current = "";  
     helper(n, 0, 0, current, ret);  
     return ret;  
   }  
   void helper(int n, int leftcount, int rightcount, string current, List<string> ret)  
   {  
     if (leftcount + rightcount == n * 2)  
     {  
       ret.Add(current);  
       return;  
     }  
     if (leftcount < n)  
     {  
       helper(n, leftcount+1, rightcount, current + "(", ret);  
     }  
     if (rightcount < leftcount)
     {  
       helper(n, leftcount, rightcount + 1, current + ")", ret);  
     }  
   }  
 }  

No comments:

Post a Comment