1359. Count All Valid Pickup and Delivery Options

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

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

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.

Input: n = 3
Output: 90

Constraints:

  • 1 <= n <= 500

题意:这道题就是问一下保持每对顺数 pickup 和 delivery 顺序不动的情况下, 有多少中排列方法。 以 3 为例。 我们有 3 对的话,对第一对来说,我们有 6 个位置可选,保持顺序的话,总共有 $C_{6}^{2}$ 种组合。 对第二对来说,我们从剩下的 4 个位置来选,那么是 $C_{4}^{2}$ 种选择,最后一对的话,只有一种可能。 找出这个规律的话,为了避免重复计算,我们开一个数组,正着算一遍即可。

代码

class Solution {
    public int countOrders(int n) {
        if(n == 1) return 1;
        if(n == 2) return 6;
        long[] arr = new long[n * 2 + 1];
        arr[2] = 1;
        for(int i = 4; i < arr.length; i+=2) {
            arr[i] = (i * (i- 1) / 2)  * (arr[i - 2]) % 1000000007;
        }
        return (int)arr[arr.length - 1];
    }
}

Search

    Table of Contents