题目
leetcode 78
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
代码
回溯法
//nums[c],arr_t[ind],n是代表当前要形成的数组长度(1-numsSize)
int dfs(int *nums, int c, int numsSize, int arr_t[], int ind, int n, int **arr, int *returnSize, int **returnColumnSizes) {
if (ind == n) {
arr[*returnSize] = (int *)malloc(sizeof(int) * n);
for (int i = 0; i < n; i++) {
arr[*returnSize][i] = arr_t[i];
}
(*returnColumnSizes)[*returnSize] = n;
(*returnSize)++;
for (int i = 1; i <= n; i++) {
if (nums[numsSize - i] != arr_t[n - i]) return 0;
}
if (n == numsSize) return 0;
return 1;
}
for (int i = c; i < numsSize; i++) {
arr_t[ind] = nums[i];
int flag = dfs(nums, i + 1, numsSize, arr_t, ind + 1, n, arr, returnSize, returnColumnSizes);
if (flag == 1) {
n++;
i = -1;
ind = 0;
}
}
return 0;
}
int** subsets(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){
long int len = 1;
int count = 0;
while (count < numsSize) {
len *= 2;
count++;
}
int **arr = (int **)malloc(sizeof(int *) * len);
(*returnColumnSizes) = (int *)malloc(sizeof(int) * len);
int arr_t[numsSize];
*returnSize = 0;
arr[*returnSize] = (int *)malloc(sizeof(int) * 1);
(*returnColumnSizes)[*returnSize] = 0;
(*returnSize)++;
dfs(nums, 0, numsSize, arr_t, 0, 1, arr, returnSize, returnColumnSizes);
return arr;
}