Problem
Given an array of integers of size n, print or return all the subsets of size k. (k<=n)
Examples
Example 1:
| |
Solutions
Method 1 - Recursion
This problem is similar to Subsets 1.
Algorithm
- Boolean Array: Create a boolean array with the same length as the original array. This will track which elements are included in the current subset.
- Recursive Choices: For each integer in the original array:
- Include: Set the corresponding element in the boolean array to
True. - Exclude: Set the corresponding element in the boolean array to
False.
- Include: Set the corresponding element in the boolean array to
- Recursive Calls: Make recursive calls for both options (include and exclude).
- Current Length:
- Include: If an integer is included, increment the
currentLengthby 1. - Exclude: If an integer is excluded, keep the
currentLengthunchanged.
- Include: If an integer is included, increment the
- Start Index: Track the starting index (
start) for the current subset. Increment it (start + 1) with each recursive call (both options). - Print Subset: When the
currentLengthreaches the target sizek, print the current subset based on theTrueelements in the boolean array.
Code
| |