4/03/2014

Leetcode -- Generate Parentheses

slightly improved
class Solution {  
 public:  
   vector<string> generateParenthesis(int n) {  
     vector<string> result;  
     helper(n, n, "", result);  
     return result;  
   }  
   void helper(int l, int r, string output, vector<string>& result) {  
     if(l == 0 && r == 0) {  
       result.emplace_back(output);  
       return;  
     }  
     if(l > 0) {  
       helper(l - 1, r, output + '(', result);  
     }  
     if(r > l) {  
       helper(l, r - 1, output + ')', result);  
     }  
   }  
 };  
 class Solution {  
 public:  
   vector<string> generateParenthesis(int n) {  
     vector<string> list;  
     string s;  
     generateParenthesisHelper(list, n,n, s);  
     return list;  
   }  
   void generateParenthesisHelper(vector<string>& list, int l, int r, string str) {  
     if(l == 0 && r == 0) {  
       list.emplace_back(str);  
     } else {  
     int loc = str.length();  
     if(l > 0) {  
       str += '(';  
       generateParenthesisHelper(list, l - 1, r, str);  
     }  
     if( l < r) {  
       if(str.length() > loc) {  
         str[loc] = ')';  
       } else {  
         str +=')';  
       }  
       generateParenthesisHelper(list, l, r - 1, str);  
     }  
     }  
   }  
 };  

No comments: