algorithm - 从集合中获取包含给定子集的所有大小为 N 的序列的算法
问题描述
更具体地说,我们想要输出的序列可以使输入子集中的元素与输入子集中的元素的顺序不同。
示例:假设我们有一个集合 {1, 9, 1, 5, 6, 9, 0 , 9, 9, 1, 10} 和一个输入子集 {9, 1}。我们希望找到包含输入子集的所有元素的所有大小为 3 的子集。这将返回集合 {1, 9, 1} , {9, 1, 5}, {9, 9, 1}, {9, 1, 10}。
当然,具有最低复杂度的算法是首选。
编辑:用更好的术语编辑。另外,这是我考虑的伪代码:
1. For each sequence s in the set of size n, do the following:
2. Create a list l that is a copy of the input subset i.
3. j = 0
4. For each element e in s, do the following:
5. Check if it's in i.
If it is, remove that element from l.
6. If l is empty, add s to the sequences to return,
skip to the next sequence (go to step 1)
7. Increment j.
8. if j == n, go to the next sequence (go to step 1)
这是我想出的,但是由于我们考虑每个序列而没有任何以前扫描过的序列的记忆,这需要非常多的时间。我真的不知道如何实现这样的内存,这对我来说都是全新的。
解决方案
您可以简单地找到该子集的所有出现,然后生成包含该组合的所有列表。
以python为例:
def get_Allsubsets_withSubset(original_list, N , subset):
subset_len = len(subset)
list_len = len(original_list)
index_of_occurrence = []
overflow = N - subset_len
for index in range(len(original_list)-len(subset)):
if original_list[index: index +len(subset)] == subset:
index_of_occurrence.append(index)
final_result = []
for index in index_of_occurrence:
for value in range(overflow+1):
i = index - value
final_result.append(original_list[i:i+N])
return final_result
它并不美丽,但我会说它是一个开始
推荐阅读
- r - 在 RI 中运行转换循环时,不断收到“if (t[val2, n] != t[val2, val]) { : 需要 TRUE/FALSE 的缺失值错误”
- mysql - GROUP_CONCAT 不同条件的同一列
- apache-flink - 在 Flink ProcessWindowFunction 中检查会话持续时间的全局状态
- javascript - Rest API - 拉取和过滤数据
- fortran - 在 Fortran 中检测预连接单元数的假设
- micronaut - Micronaut 分段上传 - 错误:“未指定必需参数 [CompletedFileUpload]”
- python - 矢量化 for 循环 - 需要平均不同大小的切片
- java - 使用 MQTT 将安卓设备连接到 PC (usbc-ethernet)
- kubernetes - GKE 水平自动扩缩器创建工作负载的修订
- sql - 如何插入没有小数秒的时间?