栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

LeetCode-1359. Count All Valid Pickup and Delivery Options [C++][Java]

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode-1359. Count All Valid Pickup and Delivery Options [C++][Java]

LeetCode-1359. Count All Valid Pickup and Delivery OptionsLevel up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.https://leetcode.com/problems/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

解题思路

i = 1时, f(1) = 1;

...

i = n - 1时, f(i) = f(n-1);

i = n时,

收发相连,则一共分到的间隙有g=2(n-1)+1 = 2n-1,

手法分开,则将两个点分开放在g个位置上, 取

即f(i) = f(n) = f(n-1) (c+s) = (2n-1)nf(n-1);

【C++】
class Solution {
public:
    int countOrders(int n) {
        if (n==0 || n==1) {return n;}
        vector dp(n+1);
        int m = 1e9+7;
        dp[0] = 0, dp[1] = 1 ;
        for(int i=2; i<=n; i++) {
            dp[i] = ((2*i-1) % m * dp[i-1]*i) % m;
        }
        return dp[n] ; 
    }
};

【Java】
class Solution {
    public int countOrders(int n) {
        long[] dp = new long[n+1];
        dp[0] = 0; dp[1] = 1;
        long m = (long) 1e9 + 7;       
        for (int i=2; i<=n; i++) {
            dp[i] = (2*i-1) % m * dp[i-1] * i % m;
        }
        return (int)dp[n];
    }
}

也可以少用点辅助空间

class Solution {
    public int countOrders(int n) {
        if (n <= 0) {return 0;}
        long dp = 1;
        long m = (long) 1e9 + 7;       
        for (int i=2; i<=n; i++) {
            dp = (2*i-1) % m * dp * i % m; //注意%m的位置
        }
        return (int)dp;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/739024.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号