Here's a code snippet in C++ that uses recursion to find all the subsets of an array:
#include <iostream>
#include <vector>
using namespace std;
// Recursive function to find subsets
void findSubsets(vector<int>& nums, vector<int>& subset, int index) {
// Print the current subset
for (int num : subset) {
cout << num << " ";
}
cout << endl;
// Generate subsets by including the current element
for (int i = index; i < nums.size(); i++) {
subset.push_back(nums[i]);
findSubsets(nums, subset, i + 1);
subset.pop_back();
}
}
// Function to find subsets of an array
void subsets(vector<int>& nums) {
vector<int> subset;
findSubsets(nums, subset, 0);
}
// Main function
int main() {
vector<int> nums = {1, 2, 3};
subsets(nums);
return 0;
}
Output:
1
1 2
1 2 3
1 3
2
2 3
3
Explanation:
The code uses recursion to explore all possible combinations of elements in the input array. At each step, we either include the current element in the subset or exclude it, leading to the generation of all possible subsets. The recursion stops when we reach the end of the input array, and we backtrack by removing the last element to explore other possibilities. The base case for the recursion is when we have processed all elements in the array, and at that point, we print the generated subset.
The output shows all the subsets of the input array '{1, 2, 3}'. Each line represents a different subset, and the numbers separated by spaces indicate the elements included in that particular subset.
153 videos|115 docs|24 tests
|
|
Explore Courses for Software Development exam
|