我必须在 C++ 应用程序中不重复地找到所有使用 3 个整数的组合。
当我指定我有多少个整数时,我可以计算出有多少种组合。
unsigned int combinations(unsigned int n){
return ((n/3) * ((n-1)/2) * (n-2));
}
但是我怎样才能将所有这些组合添加到 vector
中呢? f.e 使用:1
,2
,3
,4
: 123
,234
、124
、134
。顺序并不重要,123
与 321
相同。
最佳答案
#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::array
或 std::tuple
。我没有在这里,因为它在许多编译器上尚不可用或默认。
关于c++ - 查找所有不重复的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19751682/