LeetCode 1359. Count All Valid Pickup and Delivery Options
原题链接在这里:https://leetcode.com/problems/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
题解:
Consider we already have n - 1 pairs sequence, for the nth pair, pickup we have 2 * n - 1 positions. delivery we have 2 * n positions.
e.g. n - 1 = 1, we have p1, d1 sequence. For n = 2, we have (2 * 2 -1) = 3 positions to place p2.
_, p1, d1,
p1, _, d1,
p1, d1, _,
For d2, assume, we already placed p2, we have 2 * 2 = 4 positions to place d2.
assume, we put p2, p1, d1. there are *, p2, * p1, *, d1, * options. * represent the possible places to place d2.
So, we have (2 * n - 1) * 2 * n permutations. But d2 must come after p2, so need to divide by 2 and we get (2 * n - 1) * n.
Time Complexity: O(n).
Space: O(1).
AC Java:
1 class Solution { 2 public int countOrders(int n) { 3 long mod = (long)1e9 + 7; 4 long res = 1; 5 for(int i = 2; i <= n; i++){ 6 res = res * (i * 2 - 1) * i % mod; 7 } 8 9 return (int)res; 10 } 11 }