LeetCode 题解工作台
有效的快递序列数目
给你 n 笔订单,每笔订单都需要快递服务。 计算所有有效的 取货 / 交付 可能的顺序,使 delivery(i) 总是在 pickup(i) 之后。 由于答案可能很大,请返回答案对 10^9 + 7 取余的结果。 示例 1: 输入: n = 1 输出: 1 解释: 只有一种序列 (P1, D1),…
3
题型
5
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们定义 表示 个订单的所有有效的收件/配送序列的数目。初始时 $f[1] = 1$。 我们可以选择这 个订单中的任意一个作为最后一个配送的订单 ,那么它的收件订单 可以在之前 $2 \times i - 1$ 的任意一个位置,剩下的 $i - 1$ 个订单的配送/收件序列数目为 $f[i - 1]$,所以 可以表示为:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你 n 笔订单,每笔订单都需要快递服务。
计算所有有效的 取货 / 交付 可能的顺序,使 delivery(i) 总是在 pickup(i) 之后。
由于答案可能很大,请返回答案对 10^9 + 7 取余的结果。
示例 1:
输入:n = 1 输出:1 解释:只有一种序列 (P1, D1),物品 1 的配送服务(D1)在物品 1 的收件服务(P1)后。
示例 2:
输入:n = 2 输出:6 解释:所有可能的序列包括: (P1,P2,D1,D2),(P1,P2,D2,D1),(P1,D1,P2,D2),(P2,P1,D1,D2),(P2,P1,D2,D1) 和 (P2,D2,P1,D1)。 (P1,D2,P2,D1) 是一个无效的序列,因为物品 2 的收件服务(P2)不应在物品 2 的配送服务(D2)之后。
示例 3:
输入:n = 3 输出:90
提示:
1 <= n <= 500
解题思路
方法一:动态规划
我们定义 表示 个订单的所有有效的收件/配送序列的数目。初始时 。
我们可以选择这 个订单中的任意一个作为最后一个配送的订单 ,那么它的收件订单 可以在之前 的任意一个位置,剩下的 个订单的配送/收件序列数目为 ,所以 可以表示为:
最终的答案即为 。
我们注意到 的值只与 有关,所以可以用一个变量代替数组,降低空间复杂度。
时间复杂度 ,其中 为订单数目。空间复杂度 。
class Solution:
def countOrders(self, n: int) -> int:
mod = 10**9 + 7
f = 1
for i in range(2, n + 1):
f = (f * i * (2 * i - 1)) % mod
return f
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate should demonstrate a strong understanding of dynamic programming and combinatorics.
- question_mark
Watch for candidates applying permutations and combinations to efficiently calculate the number of valid sequences.
- question_mark
Test if the candidate can explain and handle modulo operations during the computation process.
常见陷阱
外企场景- error
Overcomplicating the problem by generating all sequences explicitly instead of using dynamic programming.
- error
Forgetting to account for the modulo 10^9 + 7 operation, leading to incorrect results due to overflow.
- error
Misunderstanding the state transition process and failing to correctly compute valid transitions between pickup and delivery pairs.
进阶变体
外企场景- arrow_right_alt
Extending the problem to account for more than one delivery per pickup, increasing the complexity.
- arrow_right_alt
Changing the constraints, such as limiting n to smaller values or increasing the range of possible values for n.
- arrow_right_alt
Modifying the problem to work with different numbers of pickups and deliveries, not tied to a one-to-one correspondence.