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 ; Initialize dp array ; Function call
dp = [ [ 0 for i in range ( 1005 ) ] for j in range ( 1005 ) ] NEW_LINE def KvisibleFromLeft ( N , K ) : NEW_LINE INDENT if ( dp [ N ] [ K ] != - 1 ) : NEW_LINE INDENT return dp [ N ] [ K ] NEW_LINE DEDENT if ( N == K ) : NEW_LINE INDENT dp [ N ] [ K ] = 1 NEW_LINE return dp [ N ] [ K ] NEW_LINE DEDENT if ( K == 1 ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT ans *= i NEW_LINE DEDENT dp [ N ] [ K ] = ans NEW_LINE return dp [ N ] [ K ] NEW_LINE DEDENT dp [ N ] [ K ] = KvisibleFromLeft ( N - 1 , K - 1 ) + ( N - 1 ) * KvisibleFromLeft ( N - 1 , K ) NEW_LINE return dp [ N ] [ K ] NEW_LINE DEDENT N , K = 5 , 2 NEW_LINE for i in range ( 1005 ) : NEW_LINE INDENT for j in range ( 1005 ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT print ( KvisibleFromLeft ( N , K ) ) NEW_LINE