0634. Find the Derangement of An Array
Description
**Input:** n = 3
**Output:** 2
**Explanation:** The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2].**Input:** n = 2
**Output:** 1ac
class Solution {
public int findDerangement(int n) {
int mod = 1000000007;
long[] dp = new long[n+1];
dp[0] = 1;
for (int i = 2; i < dp.length; i++) {
dp[i] = ((i - 1) * ((dp[i-2] + dp[i-1]) % mod)) % mod;
}
return (int)dp[n];
}
}
/*
for i, it has 2 option: 1) j-th take i-value, i take j-value, then we have dp[n-1] possible; 2) j-th take i-value, i dont' take j-value, we have dp[n-1] possible; 3) we have (i-1) j-th position, so dp[i] = (i-1) * (dp[i-1] + dp[i-2]);
*/Last updated