查找所有组合,无需重复

Find all combinations without repetition

本文关键字:组合 查找      更新时间:2023-10-16

我必须在应用程序中找到使用 3 个整数的所有组合C++而不会重复。

当我指定我有多少个整数时,我可以计算出有多少个组合。

unsigned int combinations(unsigned int n){
    return ((n/3) * ((n-1)/2) * (n-2));
}

但是我怎样才能vector所有这些组合中添加呢?例如使用:1234123234124134。顺序不重要,123321相同。

#include <vector>
using namespace std;
struct tuple3 {
    int a, b, c;   
    tuple3(int a, int b, int c) : a(a), b(b), c(c) {}
};
vector<tuple3> combinations3(vector<int> n) {
    vector<tuple3> ret;
    for(vector<int>::const_iterator it1 = n.begin(); it1 < n.end(); it1++) {
        for(vector<int>::const_iterator it2 = n.begin(); it2 < it1; it2++) {
            for(vector<int>::const_iterator it3 = n.begin(); it3 < it2; it3++) {
                ret.push_back(tuple3(*it1, *it2, *it3));
            }
        }
    }
    return ret;
}

对于未来的读者:如果可以,请使用C++11 std::arraystd::tuple。我没有在这里,因为它在许多编译器上尚不可用或默认。