Here is my DP solution:

For ith element, we have switch it with one of the previous numbers 1,2,...,i-1, and for each picked number j, for the positions left except the one take by i, j can take anyone of them. So there are dp[i - 2] permutation if j can take the original position of i, and dp[i - 1] permutations if j can not take the original position of i.

Find the Derangement of an array