mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0047.全排列II.md C语言版本
This commit is contained in:
@ -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>
|
||||
|
Reference in New Issue
Block a user