print parenthesis

/**
* 3 pairs of ()()(), print all combination
*  print ()()() ()(())....
*
**/
public void printParanthesis( int left, int right, int recurLev )
{
    char parenthesis[2] = {'{', '}'};

    Vector<char> vc = new Vector<char>();

    // the first one must be '('
    if( recurLev == 0 )
    {
        vc.add( parenthesis[0] );
    }

    // when recurLev == 5, means 3 left parenthesis and 3 right parenthesis has already
    // be add to vector, the recursive call must be terminated and returned
    // and the last parenthesis must be ')'
    if( recurLev == 5 )
    {
        vc.add( parenthesis[1] );
        System.out.println( vc.toString( ) );
    }
    for( int i = 0; i < 2; i++ )
    {
        // '(' must be equal or more than ')' at any case
        if( left < right )
        {
            return;
        }
        parenthesis.add( parenthesis[i] );
        if( parenthesis[i] == '{' )
        {
            printParanthesis( left+1, right, recurLev+1 );
        }
        if( parenthesis[i] == '}' )
        {
            printParanthesis( left, right+1, recurLev+1 );
        }
    }
}

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s