/**
* 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;
//记录满足条件的path数组长度
int* length;
int cmp(const void* a1, const void* a2) {
return *((int*)a1) - *((int*)a2);
}
//回溯算法
void backtracking(int *candidates,int target,int candidatesSize,int index,int sum){
//返回条件
if(sum >= target){
if(sum == target){
int *tmp = (int*)malloc(sizeof(int) * pathSize);
for(int i = 0;i < pathSize;i++){
tmp[i] = path[i];
}
length[ansSize] = pathSize;
ans[ansSize++] = tmp;
}
return;
}
for(int j = index;j < candidatesSize;j++){
//对同一层树中使用过的元素跳过
if(j > index && candidates[j] == candidates[j-1])
continue;
//处理
path[pathSize++] = candidates[j];
sum+=candidates[j];
//递归
backtracking(candidates,target,candidatesSize,j+1,sum);
//回溯弹出
sum-=candidates[j];
pathSize--;
}
}
int** combinationSum2(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes){
//初始化变量
path = (int*)malloc(sizeof(int) * 50);
ans = (int**)malloc(sizeof(int*) * 100);
length = (int*)malloc(sizeof(int) * 100);
pathSize = 0;
ansSize = 0;
//快速排序candidates,让相同元素挨到一起
qsort(candidates, candidatesSize, sizeof(int),cmp);
//回溯
backtracking(candidates,target,candidatesSize,0,0);
//返回数组大小
*returnSize = ansSize;
*returnColumnSizes = (int*)malloc(sizeof(int) * ansSize);
for(int i = 0;i < ansSize;i++){
(*returnColumnSizes)[i] = length[i];
}
return ans;
}
LeetCode:40. 组合总和 II
最新推荐文章于 2024-09-03 18:29:17 发布