JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

In combinatorial mathematics, a derangement is a permutation of the elements of a set, such that no element appears in its original position.

You are given an integer n. There is originally an array consisting of n integers from 1 to n in ascending order, return the number of derangements it can generate. Since the answer may be huge, return it modulo 109+7.

Example 1:

Input: n = 3
Output: 2
Explanation: The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2].

Example 2:

Input: n = 2
Output: 1

Constraints:

  • 1<=n<=106

Code

Derangement: 错排问题(伯努利-欧拉装错信封问题) - 组合数学

D(n)=(n1)(D(n2)+D(n1)) D(1)=0;D(2)=1

class Solution {
    public int findDerangement(int n) {
        if (n == 0) return 1;
        if (n == 1) return 0;

        int mod = 1000000007;

        long[] dp = new long[n + 1];
        dp[1] = 0;
        dp[2] = 1;
        for (int i = 3; i <= n; i++) {
            dp[i] = (dp[i - 2] + dp[i - 1]) * (i - 1) % mod;
        }

        return (int)dp[n];
    }
}
class Solution {
    public int findDerangement(int n) {
        if (n == 0) return 1;
        if (n == 1) return 0;

        int mod = 1000000007;

        long first = 0;
        long second = 1;
        for (int i = 3; i <= n; i++) {
            long temp = second;
            second = (first + second) * (i - 1) % mod;
            first = temp;
        }

        return (int)second;
    }
}