LeetCode //C - 78. Subsets

本文详述了如何计算并生成给定整数数组中所有独特子集的解决方案,涉及二进制表示法和内存管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:
  1. Calculate the total number of subsets as 2^n (where n is numsSize), since each element can either be present or absent.

  2. Allocate memory for the result array and the array that will hold the sizes of each subset.

  3. 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.
  1. 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值