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
Include Libraries: Include the necessary libraries for input and output, and for using vectors.
Define Function to Generate Subsets: Define a function
generateSubsets
to recursively generate subsets of the input arraynums
.Base Case: If the index is equal to the size of the array
nums
, push the current subset into thesubsets
vector and return.Include Current Element: Add the current element at the index to the
current
subset and recursively callgenerateSubsets
with the next index.Exclude Current Element: Remove the last element from the
current
subset and recursively callgenerateSubsets
with the next index.Main Function: In the
main
function, define the input arraynums
, an emptycurrent
subset, and an emptysubsets
vector. Call thegenerateSubsets
function with the initial index as 0.Output: Output all the generated subsets to the console.