LeetCode 78. 子集 Subsets(C语言)

这篇博客讨论了LeetCode的78题,即如何找出整数数组的所有子集(幂集)。博主提供了三种解法:回溯算法、迭代和位运算。每种方法都详细解释了思路,并附有运行时间。对于回溯算法,通过递归和临时存储来找到所有子集;迭代方法通过增加前n个子集的元素数量达到目的;位运算是将问题转换为遍历,根据数字的位来决定是否选中数组元素。
摘要由CSDN通过智能技术生成

题目描述:

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。

示例:

输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

题目解答:

方法1:回溯算法

循环加递归。临时数字每更新一次数字就存储一次。
运行时间ms,代码如下。

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
void dfs(int*** result, int* size, int** column, int* nums, int n, int* use, int used, int start) {
   
    int i = 0;
    for(i = start; i < n; i++) {
   
        use[used] = nums[i];
        
        (*size)++;
        column[0] = (int*)realloc(column[0], *size * sizeof(int));
        column[0][*size - 1] = used + 1;
        result[0] = (int**)realloc(result[0], *size * sizeof(int*));
        result[0][*size - 1] = (int*)malloc((used + 1) * sizeof(int));
        memcpy
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值