列印括號的合法組合
阿新 • • 發佈:2019-01-22
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); }
執行結果:
( ( ( ) ) )
( ( ) ( ) )
( ( ) ) ( )
( ) ( ( ) )
( ) ( ) ( )