Count Derangements ( Permutation such that no element appears in its original position ) | Function to count derangements ; Create an array to store counts for subproblems ; Base cases ; Fill der [ 0. . n ] in bottom up manner using above recursive formula ; Return result for n ; Driver code
function countDer ( n ) { let der = new Array ( n + 1 ) ; der [ 1 ] = 0 ; der [ 2 ] = 1 ; for ( let i = 3 ; i <= n ; ++ i ) der [ i ] = ( i - 1 ) * ( der [ i - 1 ] + der [ i - 2 ] ) ; return der [ n ] ; } let n = 4 ; document . write ( " " + countDer ( n ) ) ;