c++ - 在 C++ 中获取所有排列的最有效方法

标签 c++ combinations permutation

我正在尝试用 C++ 计算很多组合。我自己想出了下面的实现,但是效率并不理想。得到 C-18-2(每 2 个 18 的组合)需要 3 多秒,我相信这可以在更短的时间内完成。

 vector<vector<int>> Mytool::combo2(int len){
    MatrixXd ma = MatrixXd::Zero(len*len*len,2);
    int ind = 0;
    for (int i = 0 ;i<len;i++){
        for (int j = 0 ;j<len;j++){
                VectorXd v1(2);
                v1<<i,j;
                ma.row(ind) = v1;
                ind++;
        }   
    };
    ind = 0;
    vector<vector<int>> res;
    for (int i=0;i<ma.rows();i++){
        int num1 = ma(i,0);
        int num2 = ma(i,1);
        if (num1!=num2){
            vector<int> v1;
            v1.push_back(num1);
            v1.push_back(num2);
            sort(v1.begin(),v1.end());
            if (find(res.begin(),res.end(),v1)==res.end())
                res.push_back(v1);
        }
    }
    return res;
 }

任何提示或建议都会有所帮助。提前谢谢你。

最佳答案

STL 方式是使用std::next_permutation

std::vector<std::vector<int>> res;
std::vector<int> v(size - 2, 0);
v.resize(size, 1); // vector you be sorted at start : here {0, .., 0, 1, 1}.
do {
     res.push_back(v);
} while (std::next_permutation(v.begin(), v.end()));

Live example .

正如 Matthieu M 指出的那样,直接在 do while 循环中完成工作会更有效率。

关于c++ - 在 C++ 中获取所有排列的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25178689/

相关文章:

algorithm - 求等腰直角三角形的权值

c++ - 场景图、共享指针和常量传播

MySQL所有可能的组合形成多个表

python : Solving a problem of finding a combination which satisfies a particular condition

python - 在 python 中组合列表

Java 排列赋值

c++ - 在扩展模块中为用户定义的 python 类 boost Python to_python_converter

c++ - 存储点的四叉树移动

C++如何定义嵌套类中的运算符

python - 具有顺序限制的两个列表的元素的排列