LeetCode:78. Subsets 子集(C语言)

题目描述:
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答:

/**
 * 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().
 */
 #define LEN 0xffff

int num = 0;
int pos = 0;
int arr[LEN] = {0};
int size[LEN] = {0};

 void dfs(int **ret, int *nums, int numsSize, int start, int SubNum)
 {
     int i = 0;
     if(SubNum == pos)
     {
         ret[num] = malloc(sizeof(int)*numsSize); //二维数组每个数组长度为numsSize
         memcpy(ret[num], arr, sizeof(int)*numsSize);
         size[num] = SubNum;                      //每行长度
         num++;                                   //总共处理后的行数
         return;
     }

     for(i = start; i<numsSize;i++)
     {
         arr[pos++] = nums[i];  //存进一个元素,每行长度pos增加1
         dfs(ret, nums, numsSize, i+1, SubNum);
         pos--;                 //减回去
         
     }
 }
int** subsets(int* nums, int numsSize, int* returnSize, int** returnColumnSizes)
{
    int **ret = malloc(sizeof(int*)*LEN);
    int i = 0;

    num = 0;
    for(i = 0;i<=numsSize;i++)
    {
        pos = 0;    //处理后的每行长度
        dfs(ret, nums, numsSize, 0, i);
    }

    *returnSize = num;//返回行数

    *returnColumnSizes = malloc(sizeof(void*)*num);
    for(i = 0;i<num;i++)
    {
        (*returnColumnSizes)[i] = size[i];//返回的每行的长度
    }

    return ret;
}

运行结果:
在这里插入图片描述
Notes:
DFS递归

发布了124 篇原创文章 · 获赞 111 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/wangqingchuan92/article/details/104226896