思路
- 全排列得回溯
- 剪枝,当之前相等的字符串已经交换过时,剪枝
代码
void swap(char *s,int i,int j){
char temp = s[i];
s[i] = s[j];
s[j] =temp;
}
void per(int start,int end,char *s,char **res,int *returnsize){
if(start==end){
char *re =(char*)malloc(strlen(s)+1);
strcpy(re,s);
res[*returnsize] = re;
(*returnsize)++;
return;
}
int i=0;
for(i=start;i<end;i++){
int flag = 1;
for(int j = start ; j < i; j++) {
if(s[j]==s[i])
flag = 0;
}
if (flag) {
swap(s,i,start);
per(start+1,end,s,res,returnsize);
swap(s,i,start);
}
}
}
char** permutation(char* s, int* returnSize){
char **res = (char**) malloc(sizeof(char*)*10000);
int i;
*returnSize = 0;
per(0,strlen(s),s,res,returnSize);
return res;
}
|