Minimum sum possible of any bracket sequence of length N | Python 3 program to find the Minimum sum possible of any bracket sequence of length N using the given values for brackets ; DP array ; Recursive function to check for correct bracket expression ; Not a proper bracket expression ; If reaches at end ; If proper bracket expression ; if not , return max ; If already visited ; To find out minimum sum ; Driver Code
MAX_VAL = 10000000 NEW_LINE dp = [ [ - 1 for i in range ( 100 ) ] for i in range ( 100 ) ] NEW_LINE def find ( index , openbrk , n , adj ) : NEW_LINE INDENT if ( openbrk < 0 ) : NEW_LINE INDENT return MAX_VAL NEW_LINE DEDENT if ( index == n ) : NEW_LINE INDENT if ( openbrk == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return MAX_VAL NEW_LINE DEDENT DEDENT if ( dp [ index ] [ openbrk ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ openbrk ] NEW_LINE DEDENT dp [ index ] [ openbrk ] = min ( adj [ index ] [ 1 ] + find ( index + 1 , openbrk + 1 , n , adj ) , adj [ index ] [ 0 ] + find ( index + 1 , openbrk - 1 , n , adj ) ) NEW_LINE return dp [ index ] [ openbrk ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 ; NEW_LINE adj = [ [ 5000 , 3000 ] , [ 6000 , 2000 ] , [ 8000 , 1000 ] , [ 9000 , 6000 ] ] NEW_LINE print ( find ( 1 , 1 , n , adj ) + adj [ 0 ] [ 1 ] ) NEW_LINE DEDENT