Sub sets
class Solution {private: // Recursive function to generate subsets void solve(vector<int> nums, vector<int> output, int index, vector<vector<int>>& ans) { // Base case: If index reaches the size of nums, store the current subset (output) if (index >= nums.size()) { ans.push_back(output); // Store the generated subset return; }
// Exclude the current element and move to the next index solve(nums, output, index + 1, ans);
// Include the current element in the subset int element = nums[index]; output.push_back(element);
// Recur with the included element solve(nums, output, index + 1, ans); }
public: // Function to return all subsets of nums vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> ans; // Stores all subsets vector<int> output; // Temporary list to store the current subset int index = 0; // Start index for recursion solve(nums, output, index, ans); return ans; // Return the list of all subsets }};
-
he function
subsets(nums)
initializes an empty vectorans
to store the subsets. -
It calls the recursive function
solve(nums, output, index, ans)
to generate all subsets. -
Base Case: If the index reaches the size of
nums
, we add the currentoutput
(subset) to ans and return.-
Recursive Calls:
-
Exclude the current element: Move to the next index without adding nums[index] to output.
-
-
Include the current element: Add nums[index] to output and move to the next index.
-
This process ensures that all possible subsets are generated.
Example Execution with Input {1, 2, 3}
Recursive Call | Current output | Action |
---|---|---|
solve({1,2,3}, {}, 0, ans) | {} | Start |
solve({1,2,3}, {}, 1, ans) | {} | Exclude 1 |
solve({1,2,3}, {}, 2, ans) | {} | Exclude 2 |
solve({1,2,3}, {}, 3, ans) | {} | Base Case (Add {} ) |
solve({1,2,3}, {3}, 3, ans) | {3} | Include 3 |
solve({1,2,3}, {2}, 2, ans) | {2} | Include 2 |
solve({1,2,3}, {2,3}, 3, ans) | {2,3} | Include 3 |
solve({1,2,3}, {1}, 1, ans) | {1} | Include 1 |
solve({1,2,3}, {1,3}, 3, ans) | {1,3} | Include 3 |
solve({1,2,3}, {1,2}, 2, ans) | {1,2} | Include 2 |
solve({1,2,3}, {1,2,3}, 3, ans) | {1,2,3} | Include 3 |
Final Output Subsets:
{ {}, {3}, {2}, {2,3}, {1}, {1,3}, {1,2}, {1,2,3}}