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:

"((()))", "(()())", "(())()", "()(())", "()()()"

Solutions:

用二叉树表示逐步匹配的括号集合,最底层的叶子节点表示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;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值