gpt4 book ai didi

c++ - 多个列表的高效排列算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:47:38 24 4
gpt4 key购买 nike

我有可变数量的列表。每个包含不同数量的元素。

例如有四个列表,

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)1 个不同的元组,其中 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++ - 多个列表的高效排列算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13719760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com