Example:
Input: 3
Output: 5
Explanation: The following permutations are valid:
((())),(())(),()(()),(()()),()()()
The following permutations are invalid:
)()()(,())(() etc.
Program:
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{
int fun(char[],int,int,int);
int n;
cin>>n;
char A[100]="";
cout<<fun(A,0,0,n)<<endl;
}
int fun(char A[],int open,int close,int n)
{
static int count=0;
if(open-close<0 || open-close>n || open>n)
{
return count;
}
else if(strlen(A)==2*n)
{
//cout<<A<<endl;
count++;
//cout<<count<<" "<<endl;
return count;
}
else
{
A[strlen(A)]='(';
A[strlen(A)+1]=0;
fun(A,open+1,close,n);
A[strlen(A)-1]=0;
A[strlen(A)]=')';
A[strlen(A)+1]=0;
fun(A,open,close+1,n);
A[strlen(A)-1]=0;
return count;
}
}
Sample Input: 15
Sample Output: 9694845
A blog on programming and software design interview problems and solutions. Also there are some application development related stuff.
Pages
Wednesday, September 19, 2012
Counting the number of valid bracket permutations for a given length
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment