全组合(可包含重复字符)

来源:互联网 发布:淘宝网经营模式 编辑:程序博客网 时间:2024/06/03 13:55

前面写了篇博客,能够实现abc的组合,但是对于去重却没有考虑,下面实现全组合的去重算法:

 

利用链表保存结果,去除重复的串。

[cpp] view plaincopyprint?
  1. #include <iostream>   
  2. #include <string.h>   
  3. using namespace std;  
  4.   
  5. #include <iostream>   
  6. using namespace std;  
  7.   
  8. typedef struct LNode{  
  9.     char data[10];  
  10.     LNode* next;  
  11. }*List;  
  12.   
  13. void InsertList(List &l, char data[])  
  14. {  
  15.     LNode *p=new LNode;  
  16.     strcpy(p->data,data);  
  17.     if(NULL==l)  
  18.         p->next=NULL;  
  19.     else  
  20.         p->next=l;  
  21.     l=p;  
  22. }  
  23.   
  24. void Print(List l)  
  25. {  
  26.     LNode *p=l;  
  27.     while(p)  
  28.     {  
  29.         cout<<p->data<<endl;  
  30.         p=p->next;  
  31.     }  
  32. }  
  33.   
  34. bool isContain(List l, char data[])  
  35. {  
  36.     LNode *p=l;  
  37.     while(p && strcmp(p->data,data)!=0 )  
  38.         p=p->next;  
  39.   
  40.     if(!p)  
  41.         return false;  
  42.     else  
  43.         return true;  
  44.   
  45.   
  46. }  
  47.   
  48. List l=NULL;  
  49.   
  50. void Backtrack(char str[], char out[], int length, int curr, int start)//全组合  
  51. {  
  52.     for(int i=start; i<length; i++)  
  53.     {  
  54.         out[curr]=str[i];  
  55.         out[curr+1]='\0';  
  56.     //  cout<<out<<endl;       
  57.         if(!isContain(l, out))//判断是否包含此种结果,不包含则插入链表  
  58.             InsertList(l, out);  
  59.   
  60.           
  61.         if(i<length-1)  
  62.             Backtrack(str, out, length, curr+1, i+1);  
  63.     }  
  64. }  
  65.   
  66. void main()  
  67. {  
  68.     char str[]="1223";  
  69.     char *out=new char[strlen(str)+1];  
  70.     Backtrack(str, out, strlen(str), 0, 0);  
  71.   
  72.     Print(l);  
  73.       
  74.       
  75. }  

 


原创粉丝点击