针对多个列表的高效渗透算法

efficient permuation algorithm for multiple lists

本文关键字:高效 渗透 算法 列表      更新时间:2023-10-16

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

例如,有四个列表,

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 .