c++arraysrecursionintegercombinations

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


I have an array of integers, for example: 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}

Thanks in advance!


Solution

  • You can achieve all permutations of a list with comparable elements using std::next_permutation from <algorithms> library.

    The cppreference has a nice article about this: 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()));
    }