634. Find the Derangement of An Array
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
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:
Code
Derangement: 错排问题(伯努利-欧拉装错信封问题) - 组合数学
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;
}
}
按 <- 键看上一题!
633. Sum of Square Numbers
按 -> 键看下一题!
635. Design Log Storage System