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 ofderangements it can generate. Since the answer may be huge, return it
modulo109 + 7.
A derangement is a permutation where no element appears in its original position. The number of derangements for n elements, D(n), can be computed using the recurrence: D(n) = (n-1) * (D(n-1) + D(n-2)).
classSolution {
public:int findDerangement(int n) {
constint MOD =1e9+7;
if (n ==1) return0;
longlong a =1, b =0, c;
for (int i =2; i <= n; ++i) {
c = (longlong)(i -1) * (a + b) % MOD;
a = b;
b = c;
}
return b;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
funcfindDerangement(nint) int {
MOD:= int(1e9+7)
ifn==1 {
return0 }
a, b:=1, 0fori:=2; i<=n; i++ {
c:= (i-1) * (a+b) %MODa, b = b, c }
returnb}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
publicintfindDerangement(int n) {
int MOD = 1_000_000_007;
if (n == 1) return 0;
long a = 1, b = 0, c = 0;
for (int i = 2; i <= n; ++i) {
c = (i - 1) * (a + b) % MOD;
a = b;
b = c;
}
return (int)b;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funfindDerangement(n: Int): Int {
val MOD = 1_000_000_007
if (n ==1) return0var a = 1Lvar b = 0Lfor (i in2..n) {
val c = ((i - 1) * (a + b)) % MOD
a = b
b = c
}
return b.toInt()
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
deffindDerangement(self, n: int) -> int:
MOD =10**9+7if n ==1:
return0 a, b =1, 0for i in range(2, n+1):
c = (i -1) * (a + b) % MOD
a, b = b, c
return b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnfind_derangement(n: i32) -> i32 {
constMOD: i64=1_000_000_007;
if n ==1 {
return0;
}
let (mut a, mut b) = (1i64, 0i64);
for i in2..=n asi64 {
let c = (i -1) * (a + b) %MOD;
a = b;
b = c;
}
b asi32 }
}