【问题标题】:Most efficient way to get all permutations in c++在 C++ 中获取所有排列的最有效方法
【发布时间】:2014-08-07 09:19:03
【问题描述】:

我正在尝试用 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;
 }

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

【问题讨论】:

    标签: c++ combinations permutation


    【解决方案1】:

    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 循环内完成工作会更有效率。

    【讨论】:

    • 我要指出,如果可能的话,最好迭代地使用它(即,在do/while 内完成工作)而不是首先生成 然后消费。它将消除对 res 的需求,这可能最终会占用大量内存。
    • @MatthieuM.:我同意你的看法。
    • 真的很有帮助。谢谢你们!
    【解决方案2】:

    一个更简单的方法,当你使用 2 个元素的组合时,你可以使用双循环:

    std::vector<std::vector<int>> res;
    
    for (std::size_t i = 0; i != size; ++i) {
        for (std::size_t j = i + 1; j != size; ++j) {
            std::vector<int> v(size);
            v[i] = 1;
            v[j] = 1;
            res.push_back(v);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多