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:
"((()))", "(()())", "(())()", "()(())", "()()()"
用二叉树表示逐步匹配的括号集合,最底层的叶子节点表示n个正确配对的集合。
动态生成树的各个节点,
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ret;
if(n<=0)
return ret;
TreeNode *root=new TreeNode("(");
backtrack(ret, root, n, 1, 0);
delete root;
return ret;
}
private:
struct TreeNode {
string val;
TreeNode *left;
TreeNode *right;
TreeNode(string s):val(s){}
};
void backtrack(vector<string> &ret, TreeNode *root, const int n, int l, int r){
/*初次调用本函数时root为‘(’,l为1,r为0。l为root中'('的数量,r为'('的。
*函数体中动态创建左子树和右子树,左为root加上'(',右为root加上')'。
*若发现root的串已经是不正确配对的,就不必为其创建子树,如root为'())'时,不管
*后面再添加什么,都不会正确配对。
*/
if(!isPaired(root->val))
return;
if((root->val).length()==2*n) {
ret.push_back(root->val);
return ;
}
if( l < n ){
root->left=new TreeNode(root->val+"(");
backtrack(ret, root->left, n, l+1, r);
delete root->left;
root->left=NULL;
}
if( r < n ){
root->right=new TreeNode(root->val+")");
backtrack(ret, root->right, n, l, r+1);
delete root->right;
root->right=NULL;
}
}
bool isPaired(const string &s) {
//bool ret=true;
int l=0, r=0;
for(int i=0; i<s.length(); ++i) {
if(s[i]=='(')
++l;
if(s[i]==')'){
++r;
if(r>l)
return false;
}
}
return true;
}
};
还可以不用建树,直接用string。摘自http://www.cnblogs.com/codingmylife/archive/2012/09/09/2677428.html
void unguarded_generate(vector<string> &result, string curr, int m, int n)
{
if (m == 0 && n == 0)
{
result.push_back(curr);
}
else
{
if (m != 0)
{
unguarded_generate(result, curr + "(", m - 1, n);
}
if (m < n && n != 0)
{
unguarded_generate(result, curr + ")", m, n - 1);
}
}
}
vector<string> generateParenthesis(int n)
{
vector<string> ret;
if (n > 0)
{
unguarded_generate(ret, string(), n, n);
}
return ret;
}