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
def countDer ( n ) : NEW_LINE INDENT der = [ 0 for i in range ( n + 1 ) ] NEW_LINE der [ 1 ] = 0 NEW_LINE der [ 2 ] = 1 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT der [ i ] = ( i - 1 ) * ( der [ i - 1 ] + der [ i - 2 ] ) NEW_LINE DEDENT return der [ n ] NEW_LINE DEDENT n = 4 NEW_LINE print ( " Count ▁ of ▁ Derangements ▁ is ▁ " , countDer ( n ) ) NEW_LINE