找到所有组合而不重复(Find all combinations without repetition)
我必须在C ++应用程序中找到使用3个整数而不重复的所有组合。
我可以计算当我指定有多少整数时,将会有多少组合。
unsigned int combinations(unsigned int n){ return ((n/3) * ((n-1)/2) * (n-2)); }但是我如何添加vector那些所有组合呢? fe使用: 4 : 134 。 订单并不重要, 123与321相同。
I have to find all combinations using 3 integers without repetition in C++ application.
I can calculate how many combination there are going to be when I specify how many integers do I have.
unsigned int combinations(unsigned int n){ return ((n/3) * ((n-1)/2) * (n-2)); }But how can I add to vector those all combinations? f.e using: 1,2,3,4: 123,234,124, 134. The order is not important and 123 is same as 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; }对于未来的读者:如果可以的话,使用C ++ 11 std::array或std::tuple 。 我没有在这里,因为它还没有在许多编译器上可用或默认。
#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; }To future readers: Use C++11 std::array or std::tuple if you can. I did not here because it is not yet available or default on many compilers.
更多推荐
发布评论