Number of ways to partition a string into two balanced subsequences | Java implementation of the above approach ; For maximum length of input string ; Declaring the DP table ; Function to calculate the number of valid assignments ; Return 1 if both subsequences are balanced ; Increment the count if it an opening bracket ; Decrement the count if it a closing bracket ; Driver Code ; Initializing the DP table ; Initial value for c_x and c_y is zero
class GFG { static int MAX = 10 ; static int [ ] [ ] [ ] F = new int [ MAX ] [ MAX ] [ MAX ] ; static int noOfAssignments ( String s , int n , int i , int c_x , int c_y ) { if ( F [ i ] [ c_x ] [ c_y ] != - 1 ) return F [ i ] [ c_x ] [ c_y ] ; if ( i == n ) { F [ i ] [ c_x ] [ c_y ] = ( c_x == 0 && c_y == 0 ) ? 1 : 0 ; return F [ i ] [ c_x ] [ c_y ] ; } if ( s . charAt ( i ) == ' ( ' ) { F [ i ] [ c_x ] [ c_y ] = noOfAssignments ( s , n , i + 1 , c_x + 1 , c_y ) + noOfAssignments ( s , n , i + 1 , c_x , c_y + 1 ) ; return F [ i ] [ c_x ] [ c_y ] ; } F [ i ] [ c_x ] [ c_y ] = 0 ; if ( c_x != 0 ) F [ i ] [ c_x ] [ c_y ] += noOfAssignments ( s , n , i + 1 , c_x - 1 , c_y ) ; if ( c_y != 0 ) F [ i ] [ c_x ] [ c_y ] += noOfAssignments ( s , n , i + 1 , c_x , c_y - 1 ) ; return F [ i ] [ c_x ] [ c_y ] ; } public static void main ( String [ ] args ) { String s = " ( ( ) ) " ; int n = s . length ( ) ; for ( int i = 0 ; i < MAX ; i ++ ) for ( int j = 0 ; j < MAX ; j ++ ) for ( int k = 0 ; k < MAX ; k ++ ) F [ i ] [ j ] [ k ] = - 1 ; System . out . println ( noOfAssignments ( s , n , 0 , 0 , 0 ) ) ; } }