Print all valid combinations of n-pairs of parentheses.
Example:
Input: 3 (e. g. , 3 pairs of parentheses)
Output: ()()(), ()(()), (())(), ((()))
#include <iostream>
using namespace std;
static void print_n_pairs_parentheses(char str[], int l, int r, int count)
{
if (l < 0 || r < l){ // check if the params are valid
return;
}
if (l == 0 && r == 0) { // recursion finished
str[count] = '\0';
cout << str << endl;
return;
}
if (l > 0) { // try a left paren, if there are some available
str[count] = '(';
print_n_pairs_parentheses(str, l - 1, r, count + 1);
}
if (r > l) { // try a right paren, if there’s a matching left
str[count] = ')';
print_n_pairs_parentheses(str, l, r - 1, count + 1);
}
}
static void print_parentheses(int count)
{
char *str = new char[count * 2 + 1];
print_n_pairs_parentheses(str, count, count, 0);
delete [] str;
}
int main(int argc, char* argv[])
{
for(int i = 1; i < 5; i ++){
cout << "n = " << i << endl;
print_parentheses(i);
cout << endl;
}
}
Output
n = 1
()
n = 2
(())
()()
n = 3
((()))
(()())
(())()
()(())
()()()
n = 4
(((())))
((()()))
((())())
((()))()
(()(()))
(()()())
(()())()
(())(())
(())()()
()((()))
()(()())
()(())()
()()(())
()()()()