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:
"((()))", "(()())", "(())()", "()(())", "()()()"
思路:使用递归的方法,只不过在递归的时候需要注意有条件,时刻需要左边的括号比右边的括号多,只有在左边的括号比右边的多的情况下才有可能使得整个序列为合法的序列。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/*对于几对括号 有几种正确的组合方式*/
void helper(vector<char>& str,int l,int r)
{
if(l == 0 && r == 0)
{
for(int i=0;i<str.size();i++)
{
cout<<str[i];
}
cout<<endl;
}
if(l>0)
{
str.push_back('(');
helper(str,l-1,r);
str.pop_back();
}
if(r>0 && l<r)
{
str.push_back(')');
helper(str,l,r-1);
str.pop_back();
}
}
void GenerateParenthess(int n)
{
if(n<=0)
return ;
vector<char> tmp;
helper(tmp,n,n);
}
int main()
{
GenerateParenthess(3);
return 0;
}Generate Parentheses--LeetCode
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44917703