Memoization ( 1D , 2D and 3D ) | Javascript program to memoize recursive implementation of LCS problem ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] memoization applied in recursive solution ; base case ; if the same state has already been computed ; if equal , then we store the value of the function call ; store it in arr to avoid further repetitive work in future function calls ; store it in arr to avoid further repetitive work in future function calls ; Driver code
let arr = new Array ( 1000 ) ; for ( let i = 0 ; i < 1000 ; i ++ ) { arr [ i ] = new Array ( 1000 ) ; for ( let j = 0 ; j < 1000 ; j ++ ) { arr [ i ] [ j ] = - 1 ; } } function lcs ( X , Y , m , n ) { if ( m == 0 n == 0 ) return 0 ; if ( arr [ m - 1 ] [ n - 1 ] != - 1 ) return arr [ m - 1 ] [ n - 1 ] ; if ( X [ m - 1 ] == Y [ n - 1 ] ) { arr [ m - 1 ] [ n - 1 ] = 1 + lcs ( X , Y , m - 1 , n - 1 ) ; return arr [ m - 1 ] [ n - 1 ] ; } else { arr [ m - 1 ] [ n - 1 ] = Math . max ( lcs ( X , Y , m , n - 1 ) , lcs ( X , Y , m - 1 , n ) ) ; return arr [ m - 1 ] [ n - 1 ] ; } } let X = " " ; let Y = " " ; let m = X . length ; let n = Y . length ; document . write ( " " + lcs ( X , Y , m , n ) ) ;