我需要从数组中的多个数字范围生成排列。
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) 也是如此吗?范围永远不会重叠也是真的吗?
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/