本文涉及知识点
组合数学汇总
LeetCode1359. 有效的快递序列数目
给你 n 笔订单,每笔订单都需要快递服务。
计算所有有效的 取货 / 交付 可能的顺序,使 delivery(i) 总是在 pickup(i) 之后。
由于答案可能很大,请返回答案对 10^9 + 7 取余的结果。
示例 1:
输入:n = 1
输出:1
解释:只有一种序列 (P1, D1),物品 1 的配送服务(D1)在物品 1 的收件服务(P1)后。
示例 2:
输入:n = 2
输出:6
解释:所有可能的序列包括:
(P1,P2,D1,D2),(P1,P2,D2,D1),(P1,D1,P2,D2),(P2,P1,D1,D2),(P2,P1,D2,D1) 和 (P2,D2,P1,D1)。
(P1,D2,P2,D1) 是一个无效的序列,因为物品 2 的收件服务(P2)不应在物品 2 的配送服务(D2)之后。
示例 3:
输入:n = 3
输出:90
提示:
1 <= n <= 500
排列组合
n个快递,有2n个操作。必须先收,再发。 ⟺ \iff ⟺ 忽略顺序。故本题是组合。C_{2n}{2}C_{2n-2}{2} ⋯ \cdots ⋯C_22 ,为:(2n)!/2n。
代码
核心代码
template<int MOD = 1000000007>
class C1097Int
{
public:
C1097Int(long long llData = 0) :m_iData(llData% MOD)
{
}
C1097Int operator+(const C1097Int& o)const
{
return C1097Int(((long long)m_iData + o.m_iData) % MOD);
}
C1097Int& operator+=(const C1097Int& o)
{
m_iData = ((long long)m_iData + o.m_iData) % MOD;
return *this;
}
C1097Int& operator-=(const C1097Int& o)
{
m_iData = (m_iData + MOD - o.m_iData) % MOD;
return *this;
}
C1097Int operator-(const C1097Int& o)
{
return C1097Int((m_iData + MOD - o.m_iData) % MOD);
}
C1097Int operator*(const C1097Int& o)const
{
return((long long)m_iData * o.m_iData) % MOD;
}
C1097Int& operator*=(const C1097Int& o)
{
m_iData = ((long long)m_iData * o.m_iData) % MOD;
return *this;
}
C1097Int operator/(const C1097Int& o)const
{
return *this * o.PowNegative1();
}
C1097Int& operator/=(const C1097Int& o)
{
*this /= o.PowNegative1();
return *this;
}
bool operator==(const C1097Int& o)const
{
return m_iData == o.m_iData;
}
bool operator<(const C1097Int& o)const
{
return m_iData < o.m_iData;
}
C1097Int pow(long long n)const
{
C1097Int iRet = 1, iCur = *this;
while (n)
{
if (n & 1)
{
iRet *= iCur;
}
iCur *= iCur;
n >>= 1;
}
return iRet;
}
C1097Int PowNegative1()const
{
return pow(MOD - 2);
}
int ToInt()const
{
return m_iData;
}
private:
int m_iData = 0;;
};
template<class T >
class CFactorial
{
public:
CFactorial(int n):m_res(n+1){
m_res[0] = 1;
for (int i = 1; i <= n; i++) {
m_res[i] = m_res[i - 1] * i;
}
}
T Com(int iSel, int iCanSel)const {
return m_res[iCanSel] / m_res[iSel]/ m_res[iCanSel - iSel];
}
T Com(const vector<int>& cnt)const {
T biRet = 1;
int iCanSel = std::accumulate(cnt.begin(), cnt.end(), 0);
for (int j = 0; j < cnt.size(); j++) {
biRet *= Com(cnt[j], iCanSel);
iCanSel -= cnt[j];
}
return biRet;
}
vector<T> m_res;
};
class Solution {
public:
int countOrders(int n) {
CFactorial<C1097Int<>> fac(2*n);
auto res = fac.m_res[2 * n]* C1097Int<>(2).pow(n).PowNegative1();
return res.ToInt();
}
};
单元测试
TEST_METHOD(TestMethod11)
{
auto res = Solution().countOrders(1);
AssertEx(1, res);
}
TEST_METHOD(TestMethod12)
{
auto res = Solution().countOrders(2);
AssertEx(6, res);
}
TEST_METHOD(TestMethod13)
{
auto res = Solution().countOrders(3);
AssertEx(90, res);
}