[英]Getting all possible combinations of an integrer array in C++
I have an array of integers, for example: a[1,2,3]
.我有一个整数数组,例如:
a[1,2,3]
。 I would like to get all possible combinations of these numbers where they don't repeat, possibly with recursion.我想得到这些数字的所有可能组合,它们不重复,可能是递归的。
I saw something like this done with strings here: Get all combinations without duplicates but don't know how to adapt it to integers without using any standard algorithms.我在这里看到了用字符串完成的类似操作: 获取所有组合而没有重复项,但不知道如何在不使用任何标准算法的情况下将其调整为整数。
So I would like something like this as an output: {1},{2},{3},{1,2},{2,3},{1,3},{1,2,3}
所以我想要这样的输出:
{1},{2},{3},{1,2},{2,3},{1,3},{1,2,3}
Thanks in advance!提前致谢!
You can achieve all permutations of a list with comparable elements using std::next_permutation
from <algorithms>
library.您可以使用
<algorithms>
库中的std::next_permutation
实现具有可比较元素的列表的所有排列。
The cppreference has a nice article about this: https://en.cppreference.com/w/cpp/algorithm/next_permutation cppreference 有一篇关于这个的好文章: https : //en.cppreference.com/w/cpp/algorithm/next_permutation
We can use the code example to apply to your question.我们可以使用代码示例来解决您的问题。
#include <algorithm>
#include <string>
#include <iostream>
#include <vector>
void print_vector(const std::vector<int>& array) {
for (const int item : array)
{
std::cout << item << " ";
}
std::cout << std::endl;
}
int main()
{
std::vector<int> a({ 5,1,8,7,2 });
std::sort(a.begin(), a.end());
do {
print_vector(a);
} while(std::next_permutation(a.begin(), a.end()));
}
You can use std::next_permuation to achieve your goal.您可以使用std::next_permuation来实现您的目标。 Keep in mind you need to sort the array before starting to use this algorithm.
请记住,在开始使用此算法之前,您需要对数组进行排序。 The loop will exit the first time
std::next_permuation
returns false.循环将在第一次
std::next_permuation
返回 false 时退出。 If the array isn't sorted by the time you start std::next_permuation
loop, you will miss all the arrays that are lexicographically lower than the current one when entering the loop.如果在开始
std::next_permuation
循环时数组未排序,则在进入循环时将错过所有按字典顺序排列低于当前数组的数组。
int main()
{
std::vector<int> a = { 5,1,8,7,2 };
std::sort(a.begin(), a.end());
std::cout << "Possible permutations :\n";
do {
for (auto o : a)
std::cout << o;
std::cout << std::endl;
} while (std::next_permutation(a.begin(), a.end()));
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.