Leetcode c语言- Permutations II
Title:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,[1,1,2]
have the following unique permutations:
[ [1,1,2], [1,2,1], [2,1,1] ]
solutions:
/**
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
void sort(int* nums, int numsSize){
int i,j;
int flag=0;
int temp;
for (i=0;i<numsSize;i++) {
for (j=0;j<numsSize-1;j++) {
if (nums[j+1]<=nums[j]) {
temp=nums[j];
nums[j]=nums[j+1];
nums[j+1]=temp;
flag=1;
}
}
if (flag==0)
break;
}
}
void recursive(int** result,int* nums, int numsSize, int* returnSize,bool* used,int* temp, int size)
{
int i=0;
if (size==numsSize) {
result[*returnSize]=(int*)malloc(sizeof(int)*numsSize);
for (i=0;i<numsSize;i++) {
result[*returnSize][i]=temp[i];
}
size=0;
(*returnSize)++;
return;
}
for (i=0;i<numsSize;i++) {
while (nums[i]==nums[i+1] && used[i+1]==false && (i+1)<numsSize) {
i++;
}
if (!used[i]) {
used[i]=true;
temp[size]=nums[i];
recursive(result,nums,numsSize,returnSize,used,temp,size+1);
used[i]=false;
}
}
}
int** permuteUnique(int* nums, int numsSize, int* returnSize) {
int** result = (int**)malloc(sizeof(int)*1000000);
bool* used[numsSize];
int* temp[numsSize];
int size=0;
int i;
if (numsSize==0 || nums==NULL) {
*returnSize=0;
return result;
}
*returnSize=0;
memset(used,(bool)false,numsSize);
sort(nums,numsSize);
recursive(result,nums,numsSize,returnSize,used,temp,size);
return result;
}
posted on 2017-10-31 14:42 sichenzhao 阅读(433) 评论(0) 编辑 收藏 举报