打印括号的合法组合

来源:互联网 发布:php函数参考大全 pdf 编辑:程序博客网 时间:2024/05/01 09:49

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);}

运行结果:

( ( ( ) ) ) ( ( ) ( ) ) ( ( ) ) ( ) ( ) ( ( ) ) ( ) ( ) ( )