📅  最后修改于: 2023-12-03 15:37:01.500000             🧑  作者: Mango
给定一个由正整数组成的序列 nums
,和一个正整数 K
,计算出所有包含不同素数且长度最大为 K
的子序列的个数。要求时间复杂度优于 $O(2^N)$,其中 $N$ 为序列的长度。
def get_prime_factors(num):
"""返回 num 的素因数"""
factors = []
for i in range(2, int(num**0.5)+1):
if num % i == 0:
while num % i == 0:
num //= i
factors.append(i)
if num > 1:
factors.append(num)
return factors
def count_distinct_prime_subsequences(nums, K):
# 计算状态
states = [0] * len(nums)
for i, num in enumerate(nums):
factors = get_prime_factors(num)
state = 0
for factor in factors:
state |= 1 << (factor-2)
states[i] = state
# DP
f = [[0] * (1 << (K-1)) for _ in range(len(nums))]
for i in range(len(nums)):
f[i][states[i]] = 1
for s in range(1 << (K-1)):
f[i][s] += f[i-1][s]
for j in range(i):
s2 = s ^ states[i]
f[i][s] += f[j][s2]
# 统计答案
ans = 0
for i in range(len(nums)):
for s in range(1 << (K-1)):
if bin(s).count('1') == K:
ans += f[i][s]
return ans