Friday, August 12, 2011

Print all combinations of parenthesis

Given number N print all legal parenthesis combination which are possible.
for example for N = 3
( ( ( ) ) )
( ( ) ( ) )
( ( ) ) ( )
( ) ( ( ) )
( ) ( ) ( )

#include
#define N 3
int count = 0;

void printArr(int arr[]) {
int i = 0;
for (i = 0; i < N * 2 ; i++) {
if (!arr[i]) {
printf("( ");
}
else if (arr[i] == 1){
printf(") ");
}
}
printf("\n");
count++;
}

void printParanthesis(int arr[], int index, int lcount, int rcount) {
if (lcount < N) {
arr[index] = 0;
printParanthesis(arr, index + 1, lcount + 1, rcount);
}
if (lcount > rcount) {
arr[index] = 1;
if ((index + 1) == (N * 2)) {
printArr(arr);
}
else {
printParanthesis(arr, index + 1, lcount, rcount + 1);
}
}
}

No comments:

Post a Comment