leetcode - 1359. Count All Valid Pickup and Delivery Options

Description

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

Solution

Math

The total number of permutation of 2n numbers is: (2n)!, and if pick is at the front of delivery, there would be 2^n pairs. So we divide by it.

Recursive

If we have n-1 numbers, then to insert n delivery, there are 2*(n-1)+1=2n-1 choices, and to insert n pickup, there are 2*(n-1)+1+1=2n choices. Because pickup can’t be at the front of delivery, so we divide by 2.

Code

Math

class Solution:
    def countOrders(self, n: int) -> int:
        a_nn = 1
        mod_val = 1000000007
        for i in range(1, 2 * n + 1):
            a_nn *= i
        return (a_nn >> n) % mod_val

Recursive

class Solution:
    def countOrders(self, n: int) -> int:
        res = 1
        mod_val = 1000000007
        for i in range(1, n + 1):
            res *= (2 * i - 1) * i
            res %= mod_val
        return res
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值