查找所有组合,无需重复
Find all combinations without repetition
我必须在应用程序中找到使用 3 个整数的所有组合C++而不会重复。
当我指定我有多少个整数时,我可以计算出有多少个组合。
unsigned int combinations(unsigned int n){
return ((n/3) * ((n-1)/2) * (n-2));
}
但是我怎样才能vector
所有这些组合中添加呢?例如使用: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;
}
对于未来的读者:如果可以,请使用C++11 std::array
或std::tuple
。我没有在这里,因为它在许多编译器上尚不可用或默认。
相关文章:
- 从给定字符串中查找长度 k 的所有排列/组合
- 为什么查找 + 插入的组合比单个插入语句工作得更快
- 查找使用并行线程加总数的所有组合
- 快速的唯一组合(来自重复项列表),无需查找
- 查找有关当前键盘布局的字符的可能键组合
- 嵌套c++11范围循环,用于查找组合
- 将两个双数组集组合为一个查找其并集和交集的最简单方法
- 查找存储在一个数组中的数字组合,并将这些组合存储在另一个数组
- C++以广度优先搜索的方式查找多个数组中元素的所有组合
- 查找大小为 n 的所有可能的数组,这些数组由另一个数组中所有可能的元素组合以所有可能的顺序构建
- 查找所有可能的排列或具有相同顺序的组合
- 查找所有组合,无需重复
- 使用 c++ 查找回车/换行组合
- 查找列表项的组合
- 查找字符串向量的 r 组合
- 如何将查找组合的几个循环代码转换为递归方法
- 查找和存储组合
- 如何查找和替换组合框中的项
- 深度优先搜索或回溯递归查找字谜/拼字板中所有可能的字母组合
- c++使用无序键组合进行映射查找