Number of ways such that only K bars are visible from the left | dp array ; Function to calculate the number of permutations of N , where only K bars are visible from the left . ; If subproblem has already been calculated , return ; Only ascending order is possible ; N is placed at the first position The nest N - 1 are arranged in ( N - 1 ) ! ways ; Recursing ; Input ; Function call
let dp = new Array ( 1005 ) . fill ( 0 ) . map ( ( ) => new Array ( 1005 ) . fill ( - 1 ) ) ; function KvisibleFromLeft ( N , K ) { if ( dp [ N ] [ K ] != - 1 ) return dp [ N ] [ K ] ; if ( N == K ) return dp [ N ] [ K ] = 1 ; if ( K == 1 ) { let ans = 1 ; for ( let i = 1 ; i < N ; i ++ ) ans *= i ; return dp [ N ] [ K ] = ans ; } return dp [ N ] [ K ] = KvisibleFromLeft ( N - 1 , K - 1 ) + ( N - 1 ) * KvisibleFromLeft ( N - 1 , K ) ; } let N = 5 , K = 2 ; document . write ( KvisibleFromLeft ( N , K ) + " " )