首页 > 其他 > 详细

leetcode---Generate Parentheses

时间:2015-05-20 16:21:55      阅读:206      评论:0      收藏:0      [点我收藏+]

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:

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

解题思路:

求括号配对情况,我们之前讲过卡特兰数,这个组合的总个数也满足卡特兰数http://blog.csdn.net/sinat_24520925/article/details/44813119。

这道题不是问个数有多少,而是让我们子集配出所有的可能。我们利用递归的思想,左边应该有n个“(”,右边应该有n个“)”,成对产生的话,左边右边各一个。当左边“(”为0时,右边应该也配好了。具体代码如下;

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
	string str="";
	add(res,str,n,0);//n指的是开始左边未配成的括号数为n
	return res;
    }
    void add(vector<string>&res,string  str,int left,int right)
{
	if (left==0&&right==0)
	{
		res.push_back(str);
	}
	if (right>0)
	{
		add(res, str+")",left,right-1);
	}
	if (left>0)
	{
		add(res, str+"(",left-1,right+1);
	}
}
    
};




leetcode---Generate Parentheses

原文:http://blog.csdn.net/sinat_24520925/article/details/45871901

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!