Skip to content

Commit 74cfeea

Browse files
添加 0040.组合总和II.md C语言版本
1 parent 399da91 commit 74cfeea

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

problems/0040.组合总和II.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,66 @@ var combinationSum2 = function(candidates, target) {
392392
}
393393
};
394394
```
395+
C:
396+
```c
397+
int* path;
398+
int pathTop;
399+
int** ans;
400+
int ansTop;
401+
//记录ans中每一个一维数组的大小
402+
int* length;
403+
int cmp(const void* a1, const void* a2) {
404+
return *((int*)a1) - *((int*)a2);
405+
}
406+
407+
void backTracking(int* candidates, int candidatesSize, int target, int sum, int startIndex) {
408+
if(sum >= target) {
409+
//若sum等于target,复制当前path进入
410+
if(sum == target) {
411+
int* tempPath = (int*)malloc(sizeof(int) * pathTop);
412+
int j;
413+
for(j = 0; j < pathTop; j++) {
414+
tempPath[j] = path[j];
415+
}
416+
length[ansTop] = pathTop;
417+
ans[ansTop++] = tempPath;
418+
}
419+
return ;
420+
}
421+
422+
int i;
423+
for(i = startIndex; i < candidatesSize; i++) {
424+
//对同一层树中使用过的元素跳过
425+
if(i > startIndex && candidates[i] == candidates[i-1])
426+
continue;
427+
path[pathTop++] = candidates[i];
428+
sum += candidates[i];
429+
backTracking(candidates, candidatesSize, target, sum, i + 1);
430+
//回溯
431+
sum -= candidates[i];
432+
pathTop--;
433+
}
434+
}
395435

436+
int** combinationSum2(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes){
437+
path = (int*)malloc(sizeof(int) * 50);
438+
ans = (int**)malloc(sizeof(int*) * 100);
439+
length = (int*)malloc(sizeof(int) * 100);
440+
pathTop = ansTop = 0;
441+
//快速排序candidates,让相同元素挨到一起
442+
qsort(candidates, candidatesSize, sizeof(int), cmp);
443+
444+
backTracking(candidates, candidatesSize, target, 0, 0);
445+
446+
*returnSize = ansTop;
447+
*returnColumnSizes = (int*)malloc(sizeof(int) * ansTop);
448+
int i;
449+
for(i = 0; i < ansTop; i++) {
450+
(*returnColumnSizes)[i] = length[i];
451+
}
452+
return ans;
453+
}
454+
```
396455
397456
-----------------------
398457
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)

0 commit comments

Comments
 (0)