1359. Count All Valid Pickup and Delivery Options Hard
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
class Solution { public int countOrders(int n) { long result = 0; return (int)dfs(n, n, new long[n + 1][n + 1]); } private long dfs(int p, int d, long[][] mem) { long mod = 1000000007; //基本条件,当p和d位0的时候只有1中选择 if(p == 0 && d == 0) return 1; //如果剩余pickup比delivery都多 不可能,负值也不可能 if(p > d || p < 0 || d < 0) return 0; if(mem[p][d] > 0) return mem[p][d]; long count = 0; //有p中方法取一个pickup,因此有: p * dfs(p - 1, d, mem) count = (p * dfs(p - 1, d, mem)) % mod; //如果pickup完成的多(剩余的少), 有d-p个可以delivery 因此 d-p种, 因此有 (d - p) * dfs(p , d - 1) 种 if(p < d) count = (count + (d - p) * dfs(p , d - 1, mem)) % mod; mem[p][d] = count; return count; } }
标签:P2,P1,mem,memo,dfs,D2,D1 From: https://www.cnblogs.com/cynrjy/p/16935274.html