排列向量

Permutating a vector

本文关键字:向量 排列      更新时间:2023-10-16

我试图获取向量的每个排列,但也使用指示子排列的除法器。我的代码中似乎有一个错误,正如您可以从我的结果中看到结束排列。

0 1 3 2 |0 2 3 1 |0 3 2 1 |都是重复的。

我也很好奇是否有一种方法可以做我正在尝试做的事情,可以接受对矢量的引用而不是制作副本。

IDEONE:http://ideone.com/fork/2v0wk3

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void permute(vector<int> v, int path_length) {
    do {
        for(int i=0; i<=3; ++i) {
            cout << v[i] << " ";
            if(i == path_length-1)
            cout << "| ";
        }
        cout << endl;
        if(path_length == v.size()) {
            cout << "====="<< endl;
            return;
        }
        permute(v, path_length+1);
    } while(next_permutation(v.begin()+path_length-1,v.end()));
}
int main() {
    vector<int> v;
    for(int i=0;i<=3;++i)
        v.push_back(i);
    int path_length = 2;
    permute(v, path_length);
    return 0;
}

结果:

0 1 | 2 3 
0 1 2 | 3 
0 1 2 3 | 
=====
0 1 3 | 2 
0 1 3 2 | 
=====
0 1 | 3 2 
0 1 3 | 2 
0 1 3 2 | 
=====
0 2 | 1 3 
0 2 1 | 3 
0 2 1 3 | 
=====
0 2 3 | 1 
0 2 3 1 | 
=====
0 2 | 3 1 
0 2 3 | 1 
0 2 3 1 | 
=====
0 3 | 1 2 
0 3 1 | 2 
0 3 1 2 | 
=====
0 3 2 | 1 
0 3 2 1 | 
=====
0 3 | 2 1 
0 3 2 | 1 
0 3 2 1 | 
=====

预期成果:

0 1 | 2 3 
0 1 2 | 3 
0 1 2 3 | 
=====
0 1 3 | 2 
0 1 3 2 | 
=====
0 2 | 1 3 
0 2 1 | 3 
0 2 1 3 | 
=====
0 2 3 | 1 
0 2 3 1 | 
=====
0 3 | 1 2 
0 3 1 | 2 
0 3 1 2 | 
=====
0 3 2 | 1 
0 3 2 1 | 
=====

考虑另一种方法来生成您需要的每个序列。我们将有一个vector <int> cur来存储当前序列,以及一个vector <bool> used来跟踪哪些整数被使用,哪些没有。在带有depth参数的递归函数中,找到另一个未使用的整数,将其作为cur[depth],然后继续考虑下一个位置,即depth + 1。只要深度在所需范围内,就打印结果。

#include <iostream>
#include <vector>
using namespace std;
int const n = 3;
void generate (vector <int> & cur, vector <bool> & used, int depth) {
    if (depth >= 2) {
        for (int i = 0; i < depth; i++) {
            cout << cur[i] << ' ';
        }
        cout << endl;
    }
    for (int i = 0; i <= n; i++) {
        if (!used[i]) {
            used[i] = true;
            cur[depth] = i;
            generate (cur, used, depth + 1);
            used[i] = false;
        }
    }
}
int main () {
    vector <int> cur (n);
    vector <bool> used (n, false);
    cur[0] = 0;
    used[0] = true;
    generate (cur, used, 1);
    return 0;
}

输出为:

0 1 
0 1 2 
0 1 2 3 
0 1 3 
0 1 3 2 
0 2 
0 2 1 
0 2 1 3 
0 2 3 
0 2 3 1 
0 3 
0 3 1 
0 3 1 2 
0 3 2 
0 3 2 1 
您也可以

添加=====部件,如果您在depth > n时打印它。

你的问题对我来说不是很清楚。您可以使用 STL 中不太为人所知的下一个排列:

std::vector<int> my_vector = { 1 , 5 , 7 , 2 , 3 , 10};
std::sort(my_vector.begin(), my_vector.end());
do {
    std::copy(my_vector.begin(), my_vector.end(), ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;
} while(std::next_permutation(my_vector.begin(), my_vector.end()));

1 - 对向量进行排序2 - 迭代排列(做,而只是打印它与副本到cout(

我不是在乎你所谓的"子"排列,你只是在每个排列中移动"|"吗?