在 C++ 中获取整数数组的所有可能组合

Getting all possible combinations of an integrer array in C++

我有一个整数数组,例如:a[1,2,3]。我想获得这些数字的所有可能组合,其中它们不重复,可能是递归的。

我在这里看到了类似这样用字符串完成的事情: 但不知道如何在不使用任何标准算法的情况下将其调整为整数。

所以我想要这样的输出:{1},{2},{3},{1,2},{2,3},{1,3},{1,2,3}

提前致谢!

您可以使用 <algorithms> 库中的 std::next_permutation 实现具有可比较元素的列表的所有排列。

cppreference 有一篇关于此的好文章:https://en.cppreference.com/w/cpp/algorithm/next_permutation

我们可以使用代码示例来解决您的问题。

#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()));
}

您可以使用 std::next_permuation 来实现您的目标。 请记住,在开始使用此算法之前,您需要对数组进行排序。 循环将在第一次 std::next_permuation returns false 时退出。 如果在开始 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;
    }