mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0078.子集.md C语言版本
This commit is contained in:
@ -263,6 +263,63 @@ var subsets = function(nums) {
|
||||
};
|
||||
```
|
||||
|
||||
C:
|
||||
```c
|
||||
int* path;
|
||||
int pathTop;
|
||||
int** ans;
|
||||
int ansTop;
|
||||
//记录二维数组中每个一维数组的长度
|
||||
int* length;
|
||||
//将当前path数组复制到ans中
|
||||
void copy() {
|
||||
int* tempPath = (int*)malloc(sizeof(int) * pathTop);
|
||||
int i;
|
||||
for(i = 0; i < pathTop; i++) {
|
||||
tempPath[i] = path[i];
|
||||
}
|
||||
ans = (int**)realloc(ans, sizeof(int*) * (ansTop+1));
|
||||
length[ansTop] = pathTop;
|
||||
ans[ansTop++] = tempPath;
|
||||
}
|
||||
|
||||
void backTracking(int* nums, int numsSize, int startIndex) {
|
||||
//收集子集,要放在终止添加的上面,否则会漏掉自己
|
||||
copy();
|
||||
//若startIndex大于数组大小,返回
|
||||
if(startIndex >= numsSize) {
|
||||
return;
|
||||
}
|
||||
int j;
|
||||
for(j = startIndex; j < numsSize; j++) {
|
||||
//将当前下标数字放入path中
|
||||
path[pathTop++] = nums[j];
|
||||
backTracking(nums, numsSize, j+1);
|
||||
//回溯
|
||||
pathTop--;
|
||||
}
|
||||
}
|
||||
|
||||
int** subsets(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){
|
||||
//初始化辅助变量
|
||||
path = (int*)malloc(sizeof(int) * numsSize);
|
||||
ans = (int**)malloc(0);
|
||||
length = (int*)malloc(sizeof(int) * 1500);
|
||||
ansTop = pathTop = 0;
|
||||
//进入回溯
|
||||
backTracking(nums, numsSize, 0);
|
||||
//设置二维数组中元素个数
|
||||
*returnSize = ansTop;
|
||||
//设置二维数组中每个一维数组的长度
|
||||
*returnColumnSizes = (int*)malloc(sizeof(int) * ansTop);
|
||||
int i;
|
||||
for(i = 0; i < ansTop; i++) {
|
||||
(*returnColumnSizes)[i] = length[i];
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||
|
Reference in New Issue
Block a user