78. Subsets
Given an integer array nums of unique elements, return all possible
subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
- 1 <= nums.length <= 10
- -10 <= nums[i] <= 10
- All the numbers of nums are unique.
From: LeetCode
Link: 78. Subsets
Solution:
Ideas:
-
Calculate the total number of subsets as 2^n (where n is numsSize), since each element can either be present or absent.
-
Allocate memory for the result array and the array that will hold the sizes of each subset.
-
Loop through from 0 to 2^n - 1, with each iteration representing a possible subset.
- For each subset, count the number of elements (set bits in the binary representation) to determine its size.
- Allocate memory for the subset and populate it based on the current iteration’s binary representation, where a set bit means including the corresponding element from nums.
- Return the result array containing all subsets along with their sizes.
Code:
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** subsets(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {
int totalSubsets = 1 << numsSize; // 2^n subsets
int** result = (int**)malloc(totalSubsets * sizeof(int*));
*returnColumnSizes = (int*)malloc(totalSubsets * sizeof(int));
*returnSize = totalSubsets;
for (int i = 0; i < totalSubsets; ++i) {
// Count number of set bits to determine the size of this subset
int subsetSize = 0;
for (int j = 0; j < numsSize; ++j) {
if (i & (1 << j)) {
subsetSize++;
}
}
// Allocate memory for the subset
result[i] = (int*)malloc(subsetSize * sizeof(int));
(*returnColumnSizes)[i] = subsetSize;
// Fill the subset
int pos = 0;
for (int j = 0; j < numsSize; ++j) {
if (i & (1 << j)) {
result[i][pos++] = nums[j];
}
}
}
return result;
}