您的位置:首页 > 其它

打印括号的合法组合

2012-07-31 10:50 225 查看
From career up 150.

Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses.

#include <iostream>
using namespace std;

const int n = 3;
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++) {
cout << a[j] << " ";
}
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() {
print(3, 3, 0);
}


运行结果:

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