Balanced expressions such that given positions have opening brackets | Set 2 | Javascript implementation of above approach using memoization ; 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 ; Open brackets at position 1 ; Calling the find function to calculate the answer
let N = 1000 ; function find ( index , openbrk , n , dp , adj ) { if ( openbrk < 0 ) { return 0 ; } if ( index == n ) { if ( openbrk == 0 ) { return 1 ; } else { return 0 ; } } if ( dp [ index ] [ openbrk ] != - 1 ) { return dp [ index ] [ openbrk ] ; } if ( adj [ index ] == 1 ) { dp [ index ] [ openbrk ] = find ( index + 1 , openbrk + 1 , n , dp , adj ) ; } else { dp [ index ] [ openbrk ] = find ( index + 1 , openbrk + 1 , n , dp , adj ) + find ( index + 1 , openbrk - 1 , n , dp , adj ) ; } return dp [ index ] [ openbrk ] ; } let dp = new Array ( N ) ; for ( let i = 0 ; i < N ; i ++ ) { dp [ i ] = new Array ( N ) ; for ( let j = 0 ; j < N ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } let n = 2 ; let adj = [ 1 , 0 , 0 , 0 ] ; document . write ( find ( 0 , 0 , 2 * n , dp , adj ) ) ;