Number of ways to partition a string into two balanced subsequences | For maximum length of input string ; Declaring the DP table ; Declaring the prefix array ; Function to calculate the number of valid assignments ; Return 1 if X is balanced . ; Increment the count if it is an opening bracket ; Decrement the count if it is a closing bracket ; Driver code ; Creating the prefix array ; Initial value for c_x and c_y is zero
MAX = 10 NEW_LINE F = [ [ - 1 for i in range ( MAX ) ] for j in range ( MAX ) ] NEW_LINE C = [ None ] * MAX NEW_LINE def noOfAssignments ( S , n , i , c_x ) : NEW_LINE INDENT if F [ i ] [ c_x ] != - 1 : NEW_LINE INDENT return F [ i ] [ c_x ] NEW_LINE DEDENT if i == n : NEW_LINE INDENT F [ i ] [ c_x ] = not c_x NEW_LINE return F [ i ] [ c_x ] NEW_LINE DEDENT c_y = C [ i ] - c_x NEW_LINE if S [ i ] == ' ( ' : NEW_LINE INDENT F [ i ] [ c_x ] = noOfAssignments ( S , n , i + 1 , c_x + 1 ) + noOfAssignments ( S , n , i + 1 , c_x ) NEW_LINE return F [ i ] [ c_x ] NEW_LINE DEDENT F [ i ] [ c_x ] = 0 NEW_LINE if c_x : NEW_LINE INDENT F [ i ] [ c_x ] += noOfAssignments ( S , n , i + 1 , c_x - 1 ) NEW_LINE DEDENT if c_y : NEW_LINE INDENT F [ i ] [ c_x ] += noOfAssignments ( S , n , i + 1 , c_x ) NEW_LINE DEDENT return F [ i ] [ c_x ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " ( ) " NEW_LINE n = len ( S ) NEW_LINE C [ 0 ] = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if S [ i ] == ' ( ' : NEW_LINE INDENT C [ i + 1 ] = C [ i ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT C [ i + 1 ] = C [ i ] - 1 NEW_LINE DEDENT DEDENT print ( noOfAssignments ( S , n , 0 , 0 ) ) NEW_LINE DEDENT