Advertisement
centererr

balanced parenthesis

Sep 26th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<bits/stdc++.h>
  3. #define READ freopen("input.txt","r",stdin)
  4. #define WRITE freopen("output.txt","w",stdout)
  5. #define ll long long
  6. #define MAX(a,b)  a>b?a:b
  7. #define MIN(a,b)  a<b?a:b
  8. #define siz 102
  9. using namespace std ;
  10.  
  11. int  n,k;
  12. char str[100];
  13. bool isvalid()
  14. {
  15.     int k = 0;
  16.     for(int i = 0; str[i]!='\0'; i++)
  17.     {
  18.         if(str[i]=='(') k++;
  19.         else k-- ;
  20.         if(k<0) return false ;
  21.     }
  22.     if(k==0) return true;
  23.     else return false ;
  24. }
  25. void call(int l,int r)
  26. {
  27.     if(l==n&&r==n)
  28.     {
  29.         str[k]='\0';
  30.         if(isvalid())
  31.             printf("%s\n",str) ;
  32.         return ;
  33.     }
  34.     if(l<n)
  35.     {
  36.         str[k] ='(';
  37.         k++ ;
  38.         call(l+1,r);
  39.         k--;
  40.     }
  41.     if(r<n)
  42.     {
  43.         str[k] =')';
  44.         k++ ;
  45.         call(l,r+1);
  46.         k--;
  47.     }
  48.  
  49. }
  50.  
  51.  
  52. int main()
  53. {
  54.     scanf("%d",&n);
  55.     call(0,0);
  56.  
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement