求指定和的组合,但个个数只能用一次。求和一的变种,有了一的经验,二式可以沿用一式的backtracking格式,由于每个数只能用一次,那么控制参数i每次递增1就可以了。另一个要注意的是可能有重复项而重复项可能会构成解,例如【1,1,2,5,6】target = 8,【1,1,6】是解但会出现2组【1,2,5】,因此要过滤掉用过一次的重复项,我的方法是在本层递归后将重复项跃过(因为是在递归后跃进,所以能保证是用过一次的)。
ac代码如下:
void SortThreeSum(int num[], int n, int l, int h)
{
if (l >= h)
return;
int low = l, high = h;
int temp = num[low];
while (low < high) {
while (temp < num[high] && low < high)
high--;
num[low] = num[high];
while (temp >= num[low] && low < high)
low++;
num[high] = num[low];
}
num[low] = temp;
SortThreeSum(num, n, l, low - 1);
SortThreeSum(num, n, low + 1, h);
}
void cbs2(int *candidates, int candidatesSize, int target, int **columnSizes, int *returnSize, int indexi, int ii, int **path, int sum, int ***result) {
if (sum == target) {
columnSizes[0][*returnSize] = indexi;
printf("indexi-->%d\n", indexi);
*returnSize += 1;
*columnSizes = (int *)realloc(*columnSizes, sizeof(int) * (*returnSize + 1));
for (int i = 0; i < columnSizes[0][*returnSize - 1]; i++) {
(*result)[*returnSize - 1][i] = path[0][i];
// printf("%d,", path[0][i]);
}
// printf("\n");
int n = target / candidates[0] + 1;
(*result) = (int **)realloc(*result, sizeof(int *) * (*returnSize + 1));
(*result)[*returnSize] = (int *)malloc(sizeof(int) * n);
// memset(*path, 0, n);
return;
}
for (int i = ii; i < candidatesSize; i++) {
// sum += candidates[i]; //注意sum不能写在循环里,而应该写在形参里,以此保持本层递归中sum的对应
if (sum + candidates[i] <= target) {
path[0][indexi] = candidates[i];
cbs2(candidates, candidatesSize, target, columnSizes, returnSize, indexi + 1, i + 1, path, sum + candidates[i], result);
}
else
return;
while (candidates[i] == candidates[i + 1] && i < candidatesSize - 1)
i++;
}
}
int** combinationSum2(int* candidates, int candidatesSize, int target, int** columnSizes, int* returnSize) {
int **result = NULL;
SortThreeSum(candidates, candidatesSize, 0, candidatesSize - 1);
int n = target / candidates[0] + 1;
result = (int **)malloc(sizeof(int *));
*result = (int *)malloc(sizeof(int) * n);
int ***threerp = &result;
*columnSizes = (int *)malloc(sizeof(int));
int ***threecp = &columnSizes;
int **path = (int **)malloc(sizeof(int *));
*path = (int *)malloc(sizeof(int) * n);
memset(*path, 0, sizeof(int) * n);
int indexi = 0, sum = 0;
int ii = 0;
cbs2(candidates, candidatesSize, target, columnSizes, returnSize, indexi, ii, path, sum, threerp);
return result;
}