634. Find the Derangement of An Array

Posted jxr041100

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了634. Find the Derangement of An Array相关的知识,希望对你有一定的参考价值。

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];
    }
};

 

以上是关于634. Find the Derangement of An Array的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Find the Derangement of An Array 找数组的错排

vue.js:634 [Vue warn]: The computed property “total“ is already defined in data. (found in <Root>)

???HDU4689???Derangement??????????????????

SDUT 2021 Winter Individual Contest - N(B-Derangement)

Gym 100971B Derangement

HDU4689Derangement (动态规划)