1359. Count All Valid Pickup and Delivery Options

133 阅读1分钟
  1. Count All Valid Pickup and Delivery Options

Hard

Given n orders, each order consist in pickup and delivery services. 

Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). 

Since the answer may be too large, return it modulo 10^9 + 7.

 

Example 1:

Input: n = 1
Output: 1
Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.

Example 2:

Input: n = 2
Output: 6
Explanation: 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 2 is after of Delivery 2.

Example 3:

Input: n = 3
Output: 90

 

Constraints:

  • 1 <= n <= 500

答案

Intuition 1

Assume we have already n - 1 pairs, now we need to insert the nth pair.
To insert the first element, there are n * 2 - 1 chioces of position。
To insert the second element, there are n * 2 chioces of position。
So there are (n * 2 - 1) * n * 2 permutations.
Considering that delivery(i) is always after of pickup(i), we need to divide 2.
So it's (n * 2 - 1) * n.

当我们以及有 n-1对数时,要再插入一对数e1,e2,
e1可选择的位置有 2 * n - 1个,
e2可选择的位置有 2 * n 个,
所以排列组合总数为 (n * 2 - 1) * n * 2
但 e1,e2要有先后顺序,所以要除以2,
故排列组合总数为 ((n * 2 - 1) * n * 2) / 2 == (n * 2 - 1) * n

func countOrders(n int) int {
    res := 1
    mod := 1000000007
    for i := 1 ; i <= n ; i++{
        res = (res * (2*i-1)*i) % mod
    }
    return res
}

Intuition 3

The total number of all permutation obviously eauqls to 2n!.
For each pair, the order is determined, so we need to divide by 2.
So the final result is (2n)!/(2^n)

2n个数,那么排列组合的总数就是 2n! 。
但每一对数,都是有顺序的,所以要除以2 ,
有n对数,所以要除以 2^n ,
故总数为 (2n)!/(2^n)