Input: n =2Output: 6Explanation: All possible orders:(P1,P2,D1,D2),(P1,P2,D2,D1),(P1,D1,P2,D2),(P2,P1,D1,D2),(P2,P1,D2,D1) and (P2,D2,P1,D1).This is an invalid order(P1,D2,P2,D1) because Pickup 2is after of Delivery 2.
For each order, the pickup must occur before its delivery. For n orders, there are 2n events (n pickups and n deliveries). The total number of ways to arrange these events such that each delivery comes after its pickup is the product of the number of ways to insert each delivery after its pickup. This leads to the formula:
ans = 1 * 3 * 5 * ... * (2n - 1) * n!
Or, more generally, ans = (2n)! / (2^n * n!).
classSolution {
public:int countOrders(int n) {
long ans =1, mod =1e9+7;
for (int i =1; i <= n; ++i) {
ans = ans * i % mod;
ans = ans * (2* i -1) % mod;
}
return (int)ans;
}
};
1
2
3
4
5
6
7
8
funccountOrders(nint) int {
ans, mod:=1, int(1e9+7)
fori:=1; i<=n; i++ {
ans = ans*i%modans = ans* (2*i-1) %mod }
returnans}
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintcountOrders(int n) {
long ans = 1, mod = (long)1e9 + 7;
for (int i = 1; i <= n; i++) {
ans = ans * i % mod;
ans = ans * (2 * i - 1) % mod;
}
return (int)ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funcountOrders(n: Int): Int {
var ans = 1Lval mod = 1_000_000_007L
for (i in1..n) {
ans = ans * i % mod
ans = ans * (2 * i - 1) % mod
}
return ans.toInt()
}
}
1
2
3
4
5
6
7
8
classSolution:
defcountOrders(self, n: int) -> int:
ans: int =1 mod: int =10**9+7for i in range(1, n +1):
ans = ans * i % mod
ans = ans * (2* i -1) % mod
return ans
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfncount_orders(n: i32) -> i32 {
letmut ans: i64=1;
let m: i64=1_000_000_007;
for i in1..=n asi64 {
ans = ans * i % m;
ans = ans * (2* i -1) % m;
}
ans asi32 }
}
1
2
- ⏰ Time complexity: `O(n)`
- 🧺 Space complexity: `O(1)`