针对多个列表的高效渗透算法
efficient permuation algorithm for multiple lists
我有可变数量的列表。每个元素都包含不同数量的元素。
例如,有四个列表,
array1 = {1, 2, 3, 4};
array2 = {a, b, c};
array3 = {X};
array4 = {2.10, 3.5, 1.2, 6.2, 0.3};
我需要找到第 i 个元素来自第 i 个列表的所有可能的元组,例如 {1,a,X,2.10}、{1,a,X,3.5},...
目前我正在使用有性能问题的递归实现。因此,我想找到一种可以更快地执行的非迭代方式。
有什么建议吗?是否有任何有效的算法(或一些伪代码)。谢谢!
到目前为止我实现的一些伪代码:
回避版本:
vector<size_t> indices; // store current indices of each list except for the last one)
permuation (index, numOfLists) { // always called with permutation(0, numOfLists)
if (index == numOfLists - 1) {
for (i = first_elem_of_last_list; i <= last_elem_of_last_list; ++i) {
foreach(indices.begin(), indices.end(), printElemAtIndex());
printElemAtIndex(last_list, i);
}
}
else {
for (i = first_elem_of_ith_list; i <= last_elem_of_ith_list; ++i) {
update_indices(index, i);
permutation(index + 1, numOfLists); // recursive call
}
}
}
非递归版本:
vector<size_t> indices; // store current indices of each list except for the last one)
permutation-iterative(index, numOfLists) {
bool forward = true;
int curr = 0;
while (curr >= 0) {
if (curr < numOfLists - 1){
if (forward)
curr++;
else {
if (permutation_of_last_list_is_done) {
curr--;
}
else {
curr++;
forward = true;
}
if (curr > 0)
update_indices();
}
}
else {
// last list
for (i = first_elem_of_last_list; i <= last_elem_of_last_list; ++i) {
foreach(indices.begin(), indices.end(), printElemAtIndex());
printElemAtIndex(last_list, i);
}
curr--;
forward = false;
}
}
}
有 O(l^n)
个不同的元组,其中l
是列表的大小,n
是列表的数量。
因此,生成所有这些不能有效地进行多项式。
可能会进行一些局部优化 - 但我怀疑在迭代和(高效)递归之间切换会产生很大的差异(如果有的话),特别是如果迭代版本试图使用堆栈 + 循环来模仿递归解决方案,这可能比硬件堆栈更不优化。
一种可能的递归方法是:
printAll(list<list<E>> listOfLists, list<E> sol):
if (listOfLists.isEmpty()):
print sol
return
list<E> currentList <- listOfLists.removeAndGetFirst()
for each element e in currentList:
sol.append(e)
printAll(listOfLists, sol) //recursively invoking with a "smaller" problem
sol.removeLast()
listOfLists.addFirst(currentList)
(1)确切地说,有l1 * l2 * ... * ln
元组,其中li是第i个列表的大小。 对于等长的列表,它衰减到l^n
.
相关文章:
- C++中高效的大型稀疏块压缩线性方程
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 如何在C++中高效地构造随机骰子
- 如何实现高效的算法来计算大型数据集的多个不同值?
- 更高效地在微控制器上对C++进行基准测试
- 从C++无序集合中高效提取元素
- 高效的字符串截断算法,按顺序删除相等的前缀和后缀
- C++中特征对角矩阵类型的高效存储
- 高效简单的结构比较运算符
- 使用 Rcpp 的高效矩阵子集
- C++ 包含特征矩阵的类的高效算术运算符重载
- CUDA 高效的 nd-array(张量)切片
- 大多数基本类型的高效二进制序列化
- 在儿童的特定情况下,向下渗透MIN二进制堆失败
- RAM高效C++属性
- 如何为球形物体和三角形地形提供高效的碰撞检测和响应
- 如何实现四个 i8 元素组的高效_mm256_madd_epi8点积
- 如何在嵌套映射(C++)中高效地查找密钥
- 在C++中高效地保存许多连续记录的图像
- 针对多个列表的高效渗透算法