In combinatorial mathematics, a derangement is a permutation of the elements of a set, such that no element appears in its original position.
There's originally an array consisting of n
integers from 1 to n
in ascending order, you need to find the number of derangement it can generate.
Also, since the answer may be very large, you should return the output mod 109 + 7.
Example 1:
Input: 3 Output: 2 Explanation: The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2].
Note:
n
is in the range of [1, 106].
思路:
dp[n]表示到n能形成的Derangement,dp[n+1]无非是多出来一个数n+1,
(1)n+1可以与0..n之间的任意1个数交换(可以确保没有重复,因为不同的Derangement至少有2位差别,与n+1交换
一位最后还是不同的);
(2)前n位数也不一定严格要求是Derangement,可以存在一位异常,及value等于index,此时等价于dp[n-1]
所以dp[n+1]=n*(dp[n]+dp[n-1])
/*
*
*/
public class Solution {
public int findDerangement(int n) {
if(n == 1) return 0;
if(n == 2) return 1;
if(n == 3) return 2;
int[] dp = new int[1+n];
dp[2] = 1;
dp[3] = 2;
for(int i=4; i<=n; i++) {
long t = ((long)dp[i-1] + dp[i-2])*(i-1);
dp[i] = (int) (t % (1e9+7));
}
return (int) (dp[n] % (10e9+7));
}
}