leetcode[22]Generate Parentheses

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

class Solution {
public:
void generate(int left, int right, string s, vector<string> &res,int n)
{
    if(left==n&&right==n)
    {
        res.push_back(s);
        return;
    }
    if(left<n)
    {
        generate(left+1, right, s+'(', res,n);
    }
    if(right<n&&left>right)
    {
        generate(left, right+1, s+')', res,n);
    }
}
vector<string> generateParenthesis(int n) 
{
    vector<string> res;
    generate(0, 0, "", res,n);
    return res;
}
};

 

posted @ 2015-02-10 13:34  Vae永Silence  阅读(114)  评论(0编辑  收藏  举报