c++ - 多个数字范围的排列

标签 c++ vector permutation

我需要从数组中的多个数字范围生成排列。

using namespace std;

int generatePermutations(vector<int> &myVector, vector<vector<int> > &swappable) {
    int i = 0, s = 0;
    for (s = 0; s < swappable.size(); s++) {
        do {
            for (i = 0; i < myVector.size(); i++) {
                printf("%i ", myVector[i]);
            }
            printf("\n");
            swappable.pop_back();
            generatePermutations(myVector, swappable);
        } while (next_permutation(myVector.begin()+swappable[s][0],
                myVector.begin()+swappable[s][1]));
    }
}

int main() {
    vector<int> myArray;
    myArray.resize(6);
    myArray[0] = 0;
    myArray[1] = 1;
    myArray[2] = 2;
    myArray[3] = 3;
    myArray[4] = 4;
    myArray[5] = 5;

    // Swappable positions (0 - first, 1 - last)
    vector<vector<int> > swappable;
    swappable.resize(2);
    swappable[0].resize(2);
    swappable[0][0] = 1; swappable[0][1] = 3;
    swappable[1].resize(2);
    swappable[1][0] = 4; swappable[1][1] = 6;
    generatePermutations(myArray, swappable);

    return 0;
}

上面的例子应该生成这样的东西:

0 1 2 3 4 5
0 2 1 3 4 5
0 1 2 3 5 4
0 2 1 3 5 4

但是它生成了这个:

0 1 2 3 4 5
0 1 2 3 4 5

最佳答案

我认为可交换的是一组可以交换的范围?那么 [[1, 3], [4, 6]] 意味着 [1, 3)(索引 1 和 2)中的任何内容都可以在该范围内交换,对于 [4, 6) 也是如此吗?范围永远不会重叠也是真的吗?

How does this look:

typedef vector<vector<int> >::const_iterator SwappableIter;
void generatePermutations(vector<int> &data,
                          SwappableIter begin, SwappableIter end)
{
  if (begin == end) {
    print(data);
  }
  else {
    vector<int>::iterator start = data.begin() + (*begin)[0],
      stop = data.begin() + (*begin)[1];
    sort(start, stop);
    do {
      generatePermutations(data, begin + 1, end);
    } while (next_permutation(start, stop));
  }
}

关于c++ - 多个数字范围的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4805278/

相关文章:

c++ - 如何将枚举值分配给用户定义的 double 变量?? C++

c++ - 运行时错误 : reference binding to null pointer of type 'std::vector<int, std::allocator<int>>' (STL_vector. h)

java - 在Java中统一生成随机排列

c++ - 大集合的第 n 个或任意组合

c++ - std::priority_queue 对比 std::set 的 Dijkstra 最短路径算法性能

c++ - 为什么两个声明的 char* 变量获得相同的地址?

c++ - 我的 vector 实现中的错误

python - 我可以在 python 上暂停 itertools,然后再继续吗?

c++ - 你如何检测你打开的文件在打开后被移动了

python - 根据角度和速度计算交点