1359. 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
Solutions
Solution: Dynamic Programming
- Time complexity: O(n2)
- Space complexity: O(n2)
JavaScript
js
/**
* @param {number} n
* @return {number}
*/
const countOrders = function (n) {
const MODULO = 10 ** 9 + 7;
const dp = Array.from({ length: n + 1 }, () => new Array(n + 1).fill(0));
const releaseOrder = (pickup, delivery) => {
if (pickup === n && delivery === n) return 1;
if (dp[pickup][delivery]) return dp[pickup][delivery];
let result = 0;
if (pickup < n) {
const count = releaseOrder(pickup + 1, delivery);
result = (result + count * (n - pickup)) % MODULO;
}
if (pickup > delivery) {
const count = releaseOrder(pickup, delivery + 1);
result = (result + count * (pickup - delivery)) % MODULO;
}
dp[pickup][delivery] = result;
return result;
};
return releaseOrder(0, 0);
};