This problem asked for the number of permutations of a set of numbers in which none of the elements remained in their original position. This problem is solvable in more than one way. One way is memoized recursion, which is the approach that most coders took. The solution I give here, however, uses the principle of inculsion-exclusion.
The principle of inclusion-exclusion gives a way of counting the number of unique items in a set of sets of items. I will give a general idea of how it works, for a more rigorous explanation, click here. Consider the Venn diagram to the right that shows three circles representing the primary colors of light and how they add together. The principle of inclusion-exclusion says that the total area covered by the three circles will be equal to the sum of the areas of each circle, minus the area of each intersection of two circles, plus the area of the intersection of all three circles. The general idea is to add the intersection of each group of an odd number of sets, and subtract the intersection of each group of an even number of sets.
Now to apply this to deranged permutations. First we need to be able to calculate the number of uniqe permutations of a set S. If S contains n elements, all of which are unique, then there exist n! permutations of S. If S contains n elements and the value v i occurs ki times in S, for i=1 through m, then the number of distinct permutations of S is given by n!/(k1!*k 2!*...*km-1!*km!). If we want to calculate the number of permutations of S when a subset of the elements in S are held in their original positions we can just remove those elements from S and then calculate the number of permutations of S with those elements removed. To calculate the number of permutations for which no element remains in its original position, we calculate the number of permutations of S in which at least one element remains in its original position, and subtract that number from the total number of permutations of S. To calculate the number of permutations for which at least one element remains in its original position we use the principle of inclusion-exclusion. The following pseudo-code demostrates how to do this, see writer's solution in the practice room for an implementation of this in C++.
long long numDerangements(S)
long long ret=numPermutations(S);
for i from 1 to the number of elements in S
for each combination, C, of i elements in S
if (i is odd) ret=ret-numPermutations(S-C);
if (i is even) ret=ret+numPermutations(S-C);
end
end
return ret;
end