Balanced expressions such that given positions have opening brackets | Set 2 | Python3 implementation of above approach using memoization ; Open brackets at position 1 ; Function to find Number of proper bracket expressions ; If open - closed brackets < 0 ; If index reaches the end of expression ; If brackets are balanced ; If already stored in dp ; If the current index has assigned open bracket ; Move forward increasing the length of open brackets ; Move forward by inserting open as well as closed brackets on that index ; return the answer ; DP array to precompute the answer ; Calling the find function to calculate the answer
N = 1000 ; NEW_LINE dp = [ [ - 1 for x in range ( N ) ] for y in range ( N ) ] ; NEW_LINE adj = [ 1 , 0 , 0 , 0 ] ; NEW_LINE def find ( index , openbrk , n ) : NEW_LINE INDENT if ( openbrk < 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( index == n ) : NEW_LINE INDENT if ( openbrk == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT if ( dp [ index ] [ openbrk ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ openbrk ] ; NEW_LINE DEDENT if ( adj [ index ] == 1 ) : NEW_LINE INDENT dp [ index ] [ openbrk ] = find ( index + 1 , openbrk + 1 , n ) ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ index ] [ openbrk ] = ( find ( index + 1 , openbrk + 1 , n ) + find ( index + 1 , openbrk - 1 , n ) ) ; NEW_LINE DEDENT return dp [ index ] [ openbrk ] ; NEW_LINE DEDENT n = 2 ; NEW_LINE print ( find ( 0 , 0 , 2 * n ) ) ; NEW_LINE