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;
}
}


![LeetCode-1359. Count All Valid Pickup and Delivery Options [C++][Java] LeetCode-1359. Count All Valid Pickup and Delivery Options [C++][Java]](http://www.mshxw.com/aiimages/31/739024.png)
