Count Derangements ( Permutation such that no element appears in its original position ) | Function to count derangements ; Base cases ; Fill der [ 0. . n ] in bottom up manner using above recursive formula ; Return result for n ; Driver code
< ? php function countDer ( $ n ) { $ der [ 1 ] = 0 ; $ der [ 2 ] = 1 ; for ( $ i = 3 ; $ i <= $ n ; ++ $ i ) $ der [ $ i ] = ( $ i - 1 ) * ( $ der [ $ i - 1 ] + $ der [ $ i - 2 ] ) ; return $ der [ $ n ] ; } $ n = 4 ; echo " Count ▁ of ▁ Derangements ▁ is ▁ " , countDer ( $ n ) ; ? >