leetcode: Count the number of cold sequences [Mathematical question: Combination numbers contain inverse element template]

1. Screenshot of the question

Insert image description here

2. Question analysis

It needs to be divided into multiple segments for filling
For a segment with length k, there are 2 ** (k - 1) ways to fill it from both ends to the middle< /span>
The combination number is just to choose which numbers to fill in which segments

3. Combination numbers include inverse element templates

MOD = 1_000_000_007
MX = 100_000

# 组合数模板
fac = [0] * MX
fac[0] = 1
for i in range(1, MX):
    fac[i] = fac[i - 1] * i % MOD

inv_fac = [0] * MX
inv_fac[MX - 1] = pow(fac[MX - 1], -1, MOD)
for i in range(MX - 1, 0, -1):
    inv_fac[i - 1] = inv_fac[i] * i % MOD

def comb(n: int, k: int) -> int: # 啥时候填
    return fac[n] * inv_fac[k] % MOD * inv_fac[n - k] % MOD

ac code

MOD = 1_000_000_007
MX = 100_000

# 组合数模板
fac = [0] * MX
fac[0] = 1
for i in range(1, MX):
    fac[i] = fac[i - 1] * i % MOD

inv_fac = [0] * MX
inv_fac[MX - 1] = pow(fac[MX - 1], -1, MOD)
for i in range(MX - 1, 0, -1):
    inv_fac[i - 1] = inv_fac[i] * i % MOD

def comb(n: int, k: int) -> int: # 啥时候填
    return fac[n] * inv_fac[k] % MOD * inv_fac[n - k] % MOD

class Solution:
    def numberOfSequence(self, n: int, a: List[int]) -> int:
        m = len(a)
        total = n - m
        ans = comb(total, a[0]) * comb(total - a[0], n - a[-1] - 1) % MOD
        total -= a[0] + n - a[-1] - 1
        e = 0
        for p, q in pairwise(a):
            k = q - p - 1
            if k:
                e += k - 1 # 长度为k的连续序列填满的种数有2 ** (k - 1)
                ans = ans * comb(total, k) % MOD
                total -= k
        return ans * pow(2, e, MOD) % MOD

Guess you like

Origin blog.csdn.net/weixin_40986490/article/details/134814458