Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,989 questions

51,934 answers

573 users

How to find all possible N combinations from a vector of numbers in C++

1 Answer

0 votes
#include <iostream>
#include <vector>

void generateCombinations(std::vector<int>& vec, std::vector<int>& temp, int start, int n) {
    if (n == 0) {
        for (int i = 0; i < temp.size(); i++) {
            std::cout << temp[i] << " ";
        }
        std::cout << "\n";
        return;
    }
    
    for (int i = start; i <= vec.size() - n; i++) {
        temp.push_back(vec[i]);
        generateCombinations(vec, temp, i + 1, n - 1);
        temp.pop_back();
    }
}

int main() {
    std::vector <int> vec { 3, 9, 0, 4, 7, 6 };
    std::vector<int> temp;
    int n = 2;
    
    generateCombinations(vec, temp, 0, n);
}





/*
run:

3 9 
3 0 
3 4 
3 7 
3 6 
9 0 
9 4 
9 7 
9 6 
0 4 
0 7 
0 6 
4 7 
4 6 
7 6 

*/

 



answered May 30, 2023 by avibootz
...