zoukankan      html  css  js  c++  java
  • 【leetcode】1359. Count All Valid Pickup and Delivery Options

    题目如下:

    Given n orders, each order consist in pickup and delivery services. 

    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

    解题思路:记dp[i]为i个订单时可以组成的配送顺序的总数。当有i+1个订单的,对于最后一个配送的订单,一共有i+1种可能,因为任何一个订单都可以最后配送。而第i+1个订单的收取则有 (2*i-1)种可能。确定了最后一个收取以及配送的订单的后, 剩下的问题就转换成i个订单的收取和配送了,所以有 dp[i+1]  = dp[i] * i * (2*i-1)。

    代码如下:

    class Solution(object):
        def countOrders(self, n):
            """
            :type n: int
            :rtype: int
            """
            dp = [0] * (n+1)
            dp[1] = 1 
            for i in range(2,n+1):
                dp[i] = i * (2*i-1) * dp[i-1]
            return dp[-1] % (10 ** 9 + 7)
  • 相关阅读:
    养生与健康
    vue + elementui 使用多选按钮实现单选功能
    生活小方
    和业务相关的工具函数
    vue + element ui开发过程中需要注意的几个点
    【转】webpack中关于source map的配置
    【转】移动前端手机输入法自带emoji表情字符处理
    webpack相关
    vue项目优化
    运维集群架构演变之美 【转】
  • 原文地址:https://www.cnblogs.com/seyjs/p/12349942.html
Copyright © 2011-2022 走看看