Implement an algorithm to print all valid (e. g. , properly opened and closed) combinations
of n-pairs of parentheses.
EXAMPLE:
input: 3 (e. g. , 3 pairs of parentheses)
of n-pairs of parentheses.
EXAMPLE:
input: 3 (e. g. , 3 pairs of parentheses)
output: ()()(), ()(()), (())(), ((())),(()())
两张方法都用了之前讲过的卡特兰数的原理
void genPar(vector<char> &vt,int sum, int beg, int end, int acc) {
//第0位置肯定放(,那么和这个左括号匹配的右括号可能的位置是2*i+1,然后按照此类方法再去处理括号里面的元素和括号外面的元素
vt[beg] = '(';
++acc;
if (beg + 1 == end && acc +1 == sum){
vt[end] = ')';
for (int j=0; j< sum; ++j)
cout<<vt[j];
cout<<endl;
return;
}
for(int i = beg + 1; i<= end; i +=2 ) {
int tmp = acc;
vt[i] = ')';
if (i - beg >=3)
genPar(vt,sum,beg+1, i - 1,acc + 1);
if (end - i >=2)
genPar(vt, sum, i+1,end,acc + i -beg );
}
}

本文介绍了如何利用卡特兰数的原理来输出所有合法的括号组合,如()()(), ()(()), (())(), ((()))和(()())。"
133486403,19048838,Python编程:Lambda函数详解与实例,"['Python', '开发语言', '函数式编程']
最低0.47元/天 解锁文章
2726

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



