您的位置:首页 > 其它

打印包含n个括号的所有合法的组合

2013-05-06 23:14 549 查看
Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses.

打印包含n个括号的所有合法的组合

#include <iostream>
using namespace std;

const int n = 100;
char a[n * 2];

void print(int l, int r, int i) {
if(l < 0 || r < l){
return;
}
if (l==0 && r==0) {
for (int j = 0; j < n * 2; j++)
{
if(a[j]==')' || a[j]=='(')
cout << a[j] << " ";
else
break;
}
cout << endl;
} else {
if (l > 0) {
a[i] = '(';
print(l - 1, r, i + 1);
}
if (r > l) {
a[i] = ')';
print(l, r - 1, i + 1);
}
}
}

int main() {
int count;
cin >> count;
print(count, count, 0);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: