/**
* 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().
*/
void backtrace(int **result, int *returnSize, int **returnColumnSizes, int *tmp, int *tmpSize, int *nums, int startIndex, int numsSize, int k)
{
if((*tmpSize) == k)
{
(*returnColumnSizes)[(*returnSize)] = k;
memcpy(result[(*returnSize)++], tmp, sizeof(int) * k);
return;
}
int i;
for(i = startIndex; i<numsSize; ++i)
{
tmp[(*tmpSize)++] = nums[i];
backtrace(result, returnSize, returnColumnSizes, tmp, tmpSize, nums, i+1, numsSize,k);
(*tmpSize)--;
}
return;
}
int** subsets(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){
*returnSize = 0;
int resLen = pow(2, numsSize);
int **result = (int **)malloc(sizeof(int *) * resLen);
*returnColumnSizes = (int *)malloc(sizeof(int) * resLen);
memset(*returnColumnSizes, 0, sizeof(int) * resLen);
int i;
for(i = 0; i<resLen; i++)
{
result[i] = (int *)malloc(sizeof(int) * numsSize);
memset(result[i], 0, sizeof(int) * numsSize);
}
int *tmp = (int *)malloc(sizeof(int) * numsSize);
memset(tmp, 0, sizeof(int) * numsSize);
int tmpSize = 0;
for(i = 0; i<=numsSize; i++)
{
backtrace(result, returnSize, returnColumnSizes, tmp, &tmpSize, nums, 0, numsSize, i);
}
free(tmp);
return result;
}
# 78. 子集
最新推荐文章于 2023-04-16 12:19:14 发布