data-structures · intermediate · ~15 min
Count fixed-point-free permutations.
Implement:
long long count_derangements(int n);
Return the number of derangements of n items (permutations with no element in its original position). D(0)=1, D(1)=0. 0 <= n <= 20.
n in [0,20].
D(n).
Two base cases and a two-term recurrence.
#include <stddef.h>
/* Number of derangements of n items (permutations with no fixed point). D(0)=1, D(1)=0. 0<=n<=20. */
long long count_derangements(int n){ (void)n; return 0; }
Only one base case (you need both D(0) and D(1)).
D(2)=1, D(3)=2, D(4)=9.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.