Memoization ( 1D , 2D and 3D ) | A 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 ; Utility function to get max of 2 integers ; Driver Code
let arr = new Array ( 100 ) ; for ( let i = 0 ; i < 100 ; i ++ ) { arr [ i ] = new Array ( 100 ) ; for ( let j = 0 ; j < 100 ; j ++ ) { arr [ i ] [ j ] = new Array ( 100 ) ; for ( let k = 0 ; k < 100 ; k ++ ) { arr [ i ] [ j ] [ k ] = - 1 ; } } } function lcs ( X , Y , Z , m , n , o ) { if ( m == 0 n == 0 o == 0 ) return 0 ; if ( arr [ m - 1 ] [ n - 1 ] [ o - 1 ] != - 1 ) return arr [ m - 1 ] [ n - 1 ] [ o - 1 ] ; if ( X [ m - 1 ] == Y [ n - 1 ] && Y [ n - 1 ] == Z [ o - 1 ] ) { arr [ m - 1 ] [ n - 1 ] [ o - 1 ] = 1 + lcs ( X , Y , Z , m - 1 , n - 1 , o - 1 ) ; return arr [ m - 1 ] [ n - 1 ] [ o - 1 ] ; } else { arr [ m - 1 ] [ n - 1 ] [ o - 1 ] = max ( lcs ( X , Y , Z , m , n - 1 , o ) , max ( lcs ( X , Y , Z , m - 1 , n , o ) , lcs ( X , Y , Z , m , n , o - 1 ) ) ) ; return arr [ m - 1 ] [ n - 1 ] [ o - 1 ] ; } } function max ( a , b ) { return ( a > b ) ? a : b ; } let X = " " ; let Y = " " ; let Z = " " ; let m = X . length ; let n = Y . length ; let o = Z . length ; document . write ( " " + lcs ( X , Y , Z , m , n , o ) ) ;