找到所有组合而不重复(Find all combinations without repetition)

编程入门 行业动态 更新时间:2024-10-13 06:17:04
找到所有组合而不重复(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.

更多推荐

本文发布于:2023-08-04 22:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1423409.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   而不   Find   combinations   repetition

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!