[LeetCode] 1359. Count All Valid Pickup and Delivery Options 有效的快递序列数目
Given n
orders, each order consists of a pickup and a delivery service.
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
这道题说是有n个订单,每个订单要安排提货 pickup,和送货 delivery 两个事件,并且要求 pickup 必须在 delivery 事件前面,问n个订单的所有 pickup 和 delivery 的合法排序有多少种。参见题目中的例子2不难理解题意,可以看出 Pi 一定在 Di 前面,实际上这道题是一道排列组合题,是要找规律的,若 n=1
时,则根据题目要求,只有一种排列,即 P1 D1
,而当 n=2
时,P2 可以加入的位置有哪些呢,其实有3个位置可以加入,如下所示:
_ P1 _ D1 _
两个字符共有3个加入位置,即 n * 2 - 1
,若此时找个位置放下了 P2,则现在场上有了三个字符,理论上应该有4个加入位置,即 n * 2
。又因为 P2 必须要在 D2 的前面,所以应该减少一半的情况,则总共有 3 * 4 / 2 = 6
种情况,即 (n * 2 - 1) * n * 2 / 2
,化简一下得到 (n * 2 - 1) * n
,这个就是递推公式,有了这个递归公式,就可以求出任意的n值了,注意别忘了结果要对 10^9 + 7
取余,参见代码如下:
解法一:
class Solution {
public:
int countOrders(int n) {
long res = 1, M = 1e9 + 7;
for (int i = 1; i <= n; ++i) {
res = res * (i * 2 - 1) * i % M;
}
return res;
}
};
再来看一种递归的写法,一行搞定碉堡了,注意这里面的类型转换,相乘之前要转为长整型 long 来避免溢出,参见代码如下:
解法二:
class Solution {
public:
int countOrders(int n) {
return n > 0 ? ((long)countOrders(n - 1) * (n * 2 - 1) * n % ((long)1e9 + 7)) : 1;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1359
参考资料:
https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options