求n组括号的排列方式 --- 卡特拉数

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, int nLeft, int nRight, string strVal, vector<string> &resVec)
{
    if (nLeft < nRight)
        return;
    if (nLeft==n && nRight==n)
        resVec.push_back(strVal);

    if (nLeft < n)
        generate(n, nLeft+1, nRight, strVal+"(", resVec);
    if (nLeft > nRight)
        generate(n, nLeft, nRight+1, strVal+")", resVec);
}
  
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        if (n < 1)
            return ans;

        generate(n, 0, 0, "", ans);

        return ans; 
    }

 

posted @ 2014-09-04 21:27  山是水的故事  阅读(255)  评论(0编辑  收藏  举报