求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; }