Skip to content

Commit beff06e

Browse files
authored
Create: 0040-combination-sum-ii.c
1 parent 84a3c6a commit beff06e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Diff for: c/0040-combination-sum-ii.c

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
void backtrack(int *candidates, int candidatesSize, int target, int start, int *current, int currentSize, int **result, int *resultSize, int *returnColumnSizes) {
2+
if (target == 0) {
3+
result[*resultSize] = (int *)malloc(currentSize * sizeof(int));
4+
returnColumnSizes[*resultSize] = currentSize;
5+
for (int i = 0; i < currentSize; i++) {
6+
result[*resultSize][i] = current[i];
7+
}
8+
(*resultSize)++;
9+
return;
10+
}
11+
12+
for (int i = start; i < candidatesSize; i++) {
13+
if (i > start && candidates[i] == candidates[i - 1]) {
14+
continue; // Skip duplicates to avoid duplicate combinations
15+
}
16+
17+
if (candidates[i] > target) {
18+
break; // Since the array is sorted, we can exit early
19+
}
20+
21+
current[currentSize] = candidates[i];
22+
backtrack(candidates, candidatesSize, target - candidates[i], i + 1, current, currentSize + 1, result, resultSize, returnColumnSizes);
23+
}
24+
}
25+
26+
int compare(const void *a, const void *b) {
27+
return (*(int *)a - *(int *)b);
28+
}
29+
30+
int** combinationSum2(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes) {
31+
qsort(candidates, candidatesSize, sizeof(int), compare);
32+
33+
int **result = (int **)malloc(1000 * sizeof(int *));
34+
int *current = (int *)malloc(candidatesSize * sizeof(int));
35+
*returnColumnSizes = (int *)malloc(1000 * sizeof(int));
36+
37+
int resultSize = 0;
38+
backtrack(candidates, candidatesSize, target, 0, current, 0, result, &resultSize, *returnColumnSizes);
39+
40+
free(current);
41+
42+
*returnSize = resultSize;
43+
return result;
44+
}

0 commit comments

Comments
 (0)