标签:
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