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].
class Solution { public: int findDerangement(int n) { /* 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. */ if(n <= 1) return 0; vector<long> dp(n+1); long mod = 1000000007; dp[2] = 1; for(int i = 3; i < dp.size(); i++){ dp[i] = (i - 1) * (dp[i - 1] + dp[i - 2]) % mod; } return dp[dp.size() - 1]; } };
时间: 2024-10-17 22:02:27