subsets of a given array

Generating Subsets of a Given Array in C++

#include <iostream>
#include <vector>
using namespace std;

void generateSubsets(vector<int>& nums, int index, vector<int>& current, vector<vector<int>>& subsets) {
    if (index == nums.size()) {
        subsets.push_back(current);
        return;
    }
    current.push_back(nums[index]);
    generateSubsets(nums, index + 1, current, subsets);
    current.pop_back();
    generateSubsets(nums, index + 1, current, subsets);
}

int main() {
    vector<int> nums = {1, 2, 3};
    vector<int> current;
    vector<vector<int>> subsets;
    generateSubsets(nums, 0, current, subsets);

    for (const auto& subset : subsets) {
        for (int num : subset) {
            cout << num << " ";
        }
        cout << endl;
    }

    return 0;
}

Explanation

  1. Include Libraries: Include the necessary libraries for input and output, and for using vectors.

  2. Define Function to Generate Subsets: Define a function generateSubsets to recursively generate subsets of the input array nums.

  3. Base Case: If the index is equal to the size of the array nums, push the current subset into the subsets vector and return.

  4. Include Current Element: Add the current element at the index to the current subset and recursively call generateSubsets with the next index.

  5. Exclude Current Element: Remove the last element from the current subset and recursively call generateSubsets with the next index.

  6. Main Function: In the main function, define the input array nums, an empty current subset, and an empty subsets vector. Call the generateSubsets function with the initial index as 0.

  7. Output: Output all the generated subsets to the console.