字符串全排列问题(递归解决有重复字符问题)

来源:互联网 发布:巅峰软件下载 编辑:程序博客网 时间:2024/06/10 07:31

前一篇博客是一个常规字符串问题的解决,如果字符串中有重复子串,如1223,如果还是用上篇博客的解决方法,就会造成重复,这里给出“去重”解法。

以空间换取时间的算法:

#include <stdio.h>void swap(char array[],int src,int dst){  char temp = array[src];  array[src] = array[dst];  array[dst] = temp;}void Permutation(char array[],int from , int to ){//  printf("start..from = %d,to = %d \n",from,to);  int i=0;  int hash[256] = {0};  if(from == to)  {    for(i=0;i<=to;i++)    {      printf("%c",array[i]);    }    printf("\n");  }  for(i=from;i<=to;i++)  {    if(hash[array[i]] == 1)      continue;    hash[array[i]] = 1;    swap(array,i,from);    Permutation(array,from+1,to);    swap(array,i,from);  }}int main(){  char str[] = "1223";  int len = sizeof(str)/sizeof(char);  Permutation(str,0,len-2);}