/**
* 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* path;
int pathSize;
//结果
int** ans;
int ansSize;
//每个子集长度
int* length;
//回溯算法
void backtracking(int *nums,int numsSize,int start,int* use){
int* temp = (int*)malloc(sizeof(int) * pathSize);
for(int i = 0;i < pathSize;i++){
temp[i] = path[i];
}
ans = (int**)realloc(ans,sizeof(int*) * (ansSize + 1));
length[ansSize] = pathSize;
ans[ansSize++] = temp;
//结束回溯判定
if(start >= numsSize){
return;
}
//回溯
for(int i = start;i < numsSize;i++){
if(i > 0 && nums[i] == nums[i-1] && use[i-1] == false)
continue;
path[pathSize++] = nums[i];
use[i] = true;
//递归
backtracking(nums,numsSize,i + 1,use);
//回溯
use[i] = false;
pathSize--;
}
}
int cmp(const void* a, const void* b) {
return *((int*)a) - *((int*)b);
}
int** subsetsWithDup(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){
//初始化
path = (int*)malloc(sizeof(int) * numsSize);
ans = (int**)malloc(0);
length = (int*)malloc(sizeof(int) * 1500);
int* use = (int*)malloc(sizeof(int) * numsSize);
pathSize = ansSize = 0;
//排序
qsort(nums,numsSize,sizeof(int),cmp);
//回溯
backtracking(nums,numsSize,0,use);
*returnSize = ansSize;
*returnColumnSizes = (int*)malloc(sizeof(int) * ansSize);
for(int i = 0; i < ansSize; i++) {
(*returnColumnSizes)[i] = length[i];
}
return ans;
}
LeetCode:90. 子集 II
最新推荐文章于 2024-08-29 16:23:51 发布