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,855 questions

51,776 answers

573 users

How to get all possible unique subsets without duplicates from an array of unique numbers in C++

1 Answer

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

void allPossibleSubsets(std::vector<int>& nums, int start, std::vector<int>& currentSubset, 
                        std::vector<std::vector<int>>& result) {
    result.push_back(currentSubset); // Add the current subset to the result
    
    for (int i = start; i < nums.size(); ++i) {
        currentSubset.push_back(nums[i]); // Include nums[i] in the subset
        allPossibleSubsets(nums, i + 1, currentSubset, result); // Recurse with the next index
        currentSubset.pop_back(); // remove the last element
    }
}

std::vector<std::vector<int>> subsets(std::vector<int>& nums) {
    std::vector<std::vector<int>> result;
    std::vector<int> currentSubset;

    allPossibleSubsets(nums, 0, currentSubset, result);
    
    return result;
}

int main() {
    std::vector<int> nums = {1, 2, 3}; // Example input
    std::vector<std::vector<int>> result = subsets(nums);

    std::cout << "All unique subsets:\n";
    for (const auto& subset : result) {
        std::cout << "[ ";
        for (int num : subset) {
            std::cout << num << " ";
        }
        std::cout << "]\n";
    }
}


 
/*
run:
 
All unique subsets:
[ ]
[ 1 ]
[ 1 2 ]
[ 1 2 3 ]
[ 1 3 ]
[ 2 ]
[ 2 3 ]
[ 3 ]

*/

 



answered Jul 10, 2025 by avibootz

Related questions

1 answer 73 views
1 answer 53 views
1 answer 67 views
1 answer 135 views
1 answer 114 views
1 answer 130 views
...