Tuesday, March 29, 2011

WAP to Print All Possible Combination of Balanced Parenthesis

# include
# define MAX_SIZE 100

void _printParenthesis(int pos, int n, int open, int close);

/* Wrapper over _printParenthesis()*/
void printParenthesis(int n)
{
if(n > 0)
_printParenthesis(0, n, 0, 0);
return;
}

void _printParenthesis(int pos, int n, int open, int close)
{
static char str[MAX_SIZE];

if(close == n)
{
printf("%s \n", str);
return;
}
else
{
if(open > close) {
str[pos] = '}';
_printParenthesis(pos+1, n, open, close+1);
}
if(open < n) {
str[pos] = '{';
_printParenthesis(pos+1, n, open+1, close);
}
}
}

/* driver program to test above functions */
int main()
{
int n = 3;
printParenthesis(n);
getchar();
return 0;
}

2 comments :

sankalp srivastava said...

A better method in java would be

import java.util.*;
public class dyke
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int p=in.nextInt();
dyke_xy(p , 0 ,"");
}
public static void dyke_xy(int left , int right , String str)
{
if(left==0&&right==0)
{
System.out.println(str);
}
else if(left>0)
{
dyke_xy(left-1 ,right+1 ,str+"(");
}
else if(right>0)
{
dyke_xy(left , right-1 , str+")");
}
return ;
}
}

Unknown said...

@sankalp yes both has same time complexity :)

Happy coding

Shashank