c++ - 查找所有不重复的组合

标签 c++ combinations

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

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

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

但是我怎样才能将所有这些组合添加到 vector 中呢? f.e 使用:1,2,3,4: 123,234124134。顺序并不重要,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;
}

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

关于c++ - 查找所有不重复的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19751682/

相关文章:

Java从列中查找所有可能的组合

mySQL获取某些行的所有可能组合

python - 如何找到参数和函数的所有可能组合

c++ - 如何使 Eclipse 错误解析器接受 cilk_for

c++ - 使用变量来决定类或命名空间的类型

python - 在 Python 中构建字典组合以匹配目标总和

c - 从字符集高效地创建顺序词表

c++ - vector::size() 如何在常数时间内返回 vector 的大小?

c++ - 折叠表达式 : iterate over variadic template type parameter to check compile-time conditions on the comprising types

c++ - 生成随机数并将它们放入数组中