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)
  • 相关阅读:
    数据分析入门_char01
    [转]在Goolge安装谷歌插件Postman
    Ubutu 14.04 Fiddler Android抓包
    Ubuntu14.04 install appium
    【转】ubuntu修改时区和时间的方法
    MongoDB权威指南<2> 1-2 MongoDB 介绍
    python数据类型-字典
    python数据类型-列表
    python数据类型-字符串
    python编码以及格式化输出
  • 原文地址:https://www.cnblogs.com/seyjs/p/12349942.html
Copyright © 2011-2022 走看看