LeetCode 题解工作台

有效的快递序列数目

给你 n 笔订单,每笔订单都需要快递服务。 计算所有有效的 取货 / 交付 可能的顺序,使 delivery(i) 总是在 pickup(i) 之后。 由于答案可能很大,请返回答案对 10^9 + 7 取余的结果。 示例 1: 输入: n = 1 输出: 1 解释: 只有一种序列 (P1, D1),…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

困难 · 状态·转移·动态规划

bolt

答案摘要

我们定义 表示 个订单的所有有效的收件/配送序列的数目。初始时 $f[1] = 1$。 我们可以选择这 个订单中的任意一个作为最后一个配送的订单 ,那么它的收件订单 可以在之前 $2 \times i - 1$ 的任意一个位置,剩下的 $i - 1$ 个订单的配送/收件序列数目为 $f[i - 1]$,所以 可以表示为:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你 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
lightbulb

解题思路

方法一:动态规划

我们定义 f[i]f[i] 表示 ii 个订单的所有有效的收件/配送序列的数目。初始时 f[1]=1f[1] = 1

我们可以选择这 ii 个订单中的任意一个作为最后一个配送的订单 DiD_i,那么它的收件订单 PiP_i 可以在之前 2×i12 \times i - 1 的任意一个位置,剩下的 i1i - 1 个订单的配送/收件序列数目为 f[i1]f[i - 1],所以 f[i]f[i] 可以表示为:

f[i]=i×(2×i1)×f[i1]f[i] = i \times (2 \times i - 1) \times f[i - 1]

最终的答案即为 f[n]f[n]

我们注意到 f[i]f[i] 的值只与 f[i1]f[i - 1] 有关,所以可以用一个变量代替数组,降低空间复杂度。

时间复杂度 O(n)O(n),其中 nn 为订单数目。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

有效的快递序列数目题解:状态·转移·动态规划 | LeetCode #1359 困难