Friday, April 12, 2013

generate parentheses (C++ code)

LeetCode Generate Parentheses, Feb 13 '12
 难度3, 出现频率4


Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"

思路:写了个简单的递归算法。

void generate(int n, vector<string> &res, string path, int left, int right){
   if(left == n && right == n){
     res.push_back(path);
     return;
   }
   if(left == right) {
     path.push_back('('); 
     generate(n,res,path,left+1,right);
   }
   else if(left == n) {
           path.push_back(')');
           generate(n,res,path,left,right+1);
        }
   else{
     path.push_back('(');
     generate(n,res,path,left+1, right);
     path.back() = ')';
     generate(n,res,path,left,right+1);
    
   }

}

 vector<string> generateParenthesis(int n) {
       vector<string> res;

       string path;
       generate(n,res,path,0,0);

       return res;
    }

No comments:

Post a Comment