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;

}

};

 

你可能感兴趣的:(LeetCode)