Microsoft Interview Question

Generate all possible parenthesis for a given n

Interview Answers

Anonymous

Sep 25, 2013

#include #include using namespace std; int count=0; void print(string str, int n, int l, int r) { if(n==0) { if(l==r) { cout l) { return; } string str1 = str + "("; string str2 = str + ")"; print(str1, n-1, l+1, r); print(str2, n-1, l, r+1); } int main() { print("", 16, 0, 0); cout << count << endl; return 0; }

Anonymous

Apr 20, 2014

#include using namespace std; string s; int n; void back(int pos,int nl){ if(pos==n){ if(nl==0) cout 0){ s += ')'; back(pos+1,nl-1); s = s.substr(0,pos); } s += '('; back(pos+1,nl+1); s = s.substr(0,pos); } } int main(){ cin>>n; back(0,0); }