[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

https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/solutions/516968/java-c-python-easy-and-concise/


LeetCode All in One 题目讲解汇总(持续更新中...)

posted @   Grandyang  阅读(88)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-11-06 [LeetCode] 1249. Minimum Remove to Make Valid Parentheses 移除无效的括号
2018-11-06 [LeetCode] Insert into a Binary Search Tree 二叉搜索树中插入结点
2018-11-06 [LeetCode] Search in a Binary Search Tree 二叉搜索树中搜索
2016-11-06 [LintCode] Single Number 单独的数字
2015-11-06 [CareerCup] 14.1 Private Constructor 私有构建函数
2014-11-06 [LeetCode] 66. Plus One 加一运算
2014-11-06 [LeetCode] 70. Climbing Stairs 爬楼梯问题
Fork me on GitHub

喜欢请打赏

扫描二维码打赏

Venmo 打赏

点击右上角即可分享
微信分享提示