问题:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
产生所有括号的组合,核心要点是如果左括号数nl>=nr右边括号数,则只能放入左括号,如果nl<nr,则当前位置可以放左或右括号。
vector<string> str;
char a='(';
char b=')';
void rankkuohao(string s, char c, int nl, int nr)
{
if( c !=' ') s.push_back(c);
if(nl==0 &&nr==0)
{
str.push_back(s);
s.clear();
};
if( nr > nl)
{
if(nl>0)
rankkuohao(s, a,nl-1, nr); //放入之后数量减一
if(nr>0)
rankkuohao(s, b, nl, nr-1);
}
else if(nl>0)
rankkuohao(s, a, nl-1, nr);
}
vector<string> generateParenthesis(int n)
{ string s;
char c=' ';
if (n<1) return str;
rankkuohao(s, c, n, n);
return str;
}
本文介绍了一种递归算法,用于生成所有可能的有效括号组合。对于给定的整数n,该算法能够生成所有由n对括号组成的正确闭合的字符串。核心思想是通过递归地添加左右括号,并确保任何时候左括号的数量不小于右括号的数量。
260

被折叠的 条评论
为什么被折叠?



