Skip to content

Commit

Permalink
Merge pull request youngyangyang04#997 from KingArthur0205/remote
Browse files Browse the repository at this point in the history
添加 0047.全排列II.md C语言版本
  • Loading branch information
youngyangyang04 authored Jan 12, 2022
2 parents 6de5da7 + 155f457 commit d236296
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions problems/0047.全排列II.md
Original file line number Diff line number Diff line change
Expand Up @@ -323,5 +323,76 @@ func permuteUnique(_ nums: [Int]) -> [[Int]] {
}
```

### C
```c
//临时数组
int *path;
//返回数组
int **ans;
int *used;
int pathTop, ansTop;

//拷贝path到ans中
void copyPath() {
int *tempPath = (int*)malloc(sizeof(int) * pathTop);
int i;
for(i = 0; i < pathTop; ++i) {
tempPath[i] = path[i];
}
ans[ansTop++] = tempPath;
}

void backTracking(int* used, int *nums, int numsSize) {
//若path中元素个数等于numsSize,将path拷贝入ans数组中
if(pathTop == numsSize)
copyPath();
int i;
for(i = 0; i < numsSize; i++) {
//若当前元素已被使用
//或前一位元素与当前元素值相同但并未被使用
//则跳过此分支
if(used[i] || (i != 0 && nums[i] == nums[i-1] && used[i-1] == 0))
continue;

//将当前元素的使用情况设为True
used[i] = 1;
path[pathTop++] = nums[i];
backTracking(used, nums, numsSize);
used[i] = 0;
--pathTop;
}
}

int cmp(void* elem1, void* elem2) {
return *((int*)elem1) - *((int*)elem2);
}

int** permuteUnique(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){
//排序数组
qsort(nums, numsSize, sizeof(int), cmp);
//初始化辅助变量
pathTop = ansTop = 0;
path = (int*)malloc(sizeof(int) * numsSize);
ans = (int**)malloc(sizeof(int*) * 1000);
//初始化used辅助数组
used = (int*)malloc(sizeof(int) * numsSize);
int i;
for(i = 0; i < numsSize; i++) {
used[i] = 0;
}

backTracking(used, nums, numsSize);

//设置返回的数组的长度
*returnSize = ansTop;
*returnColumnSizes = (int*)malloc(sizeof(int) * ansTop);
int z;
for(z = 0; z < ansTop; z++) {
(*returnColumnSizes)[z] = numsSize;
}
return ans;
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 comments on commit d236296

Please sign in to comment.