Find out different combinations of brackets


#include<iostream>
#include<math.h>

using namespace std;

int min_numb(int brack, int minbin = 0)
{
    int shift = 2*brack - 1;
    while(shift > 1)
    {
        minbin += (1<<shift);
        shift -= 2;
    }
    return (minbin+2);
}

bool isValid(int num)
{
    int count=0;
    while(num)
    {
        if(count>0)
            return false;
        if(!(num&1))
            count--;
        else
            count++;
        num = num>>1;
    }
    return true;
}

int main()
{
    int num, brack, max, min, x, j, count=0;
    cin>>num;

    brack = (1<<num) - 1; // eg., num=4, brack=1111
    max = brack<<num;     //max= 11110000 for (((())))
    min = min_numb(num);  //min = 10101010 for ()()()()

    for(x=min; x<=max; x=((x+(x&(-x)))|(((x^(x+(x&(-x)))))/(x&(-x))>>2)))
    {
    //x=((x+(x&(-x)))|(((x^(x+(x&(-x)))))/(x&(-x))>>2)) gives next higher number with same number of 1's
        if(isValid(x))
        {
            count++;
            j = x;
            while(j)
            {
                if(j&1)
                    cout<<')';
                else
                    cout<<'(';
                j= j>>1;
            }
            cout<<endl;
        }
    }
    cout<<count;
    return 0;
}

Comments

Popular Posts