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; }
本文介绍了一个生成有效括号组合的算法。给定一个正整数 n,该算法能生成所有可能的有效括号字符串。例如当 n=3 时,可以得到 ((())), (()()), (())(), ()(()) 和 ()()() 这五种有效的括号组合。
9605

被折叠的 条评论
为什么被折叠?



