前面写了篇博客,能够实现abc的组合,但是对于去重却没有考虑,下面实现全组合的去重算法:
利用链表保存结果,去除重复的串。
- #include<iostream>
- #include<string.h>
- usingnamespacestd;
- #include<iostream>
- usingnamespacestd;
- typedefstructLNode{
- chardata[10];
- LNode*next;
- }*List;
- voidInsertList(List&l,chardata[])
- {
- LNode*p=newLNode;
- strcpy(p->data,data);
- if(NULL==l)
- p->next=NULL;
- else
- p->next=l;
- l=p;
- }
- voidPrint(Listl)
- {
- LNode*p=l;
- while(p)
- {
- cout<<p->data<<endl;
- p=p->next;
- }
- }
- boolisContain(Listl,chardata[])
- {
- LNode*p=l;
- while(p&&strcmp(p->data,data)!=0)
- p=p->next;
- if(!p)
- returnfalse;
- else
- returntrue;
- }
- Listl=NULL;
- voidBacktrack(charstr[],charout[],intlength,intcurr,intstart)//全组合
- {
- for(inti=start;i<length;i++)
- {
- out[curr]=str[i];
- out[curr+1]='\0';
- //cout<<out<<endl;
- if(!isContain(l,out))//判断是否包含此种结果,不包含则插入链表
- InsertList(l,out);
- if(i<length-1)
- Backtrack(str,out,length,curr+1,i+1);
- }
- }
- voidmain()
- {
- charstr[]="1223";
- char*out=newchar[strlen(str)+1];
- Backtrack(str,out,strlen(str),0,0);
- Print(l);
- }
利用链表保存结果,去除重复的串。
- #include<iostream>
- #include<string.h>
- usingnamespacestd;
- #include<iostream>
- usingnamespacestd;
- typedefstructLNode{
- chardata[10];
- LNode*next;
- }*List;
- voidInsertList(List&l,chardata[])
- {
- LNode*p=newLNode;
- strcpy(p->data,data);
- if(NULL==l)
- p->next=NULL;
- else
- p->next=l;
- l=p;
- }
- voidPrint(Listl)
- {
- LNode*p=l;
- while(p)
- {
- cout<<p->data<<endl;
- p=p->next;
- }
- }
- boolisContain(Listl,chardata[])
- {
- LNode*p=l;
- while(p&&strcmp(p->data,data)!=0)
- p=p->next;
- if(!p)
- returnfalse;
- else
- returntrue;
- }
- Listl=NULL;
- voidBacktrack(charstr[],charout[],intlength,intcurr,intstart)//全组合
- {
- for(inti=start;i<length;i++)
- {
- out[curr]=str[i];
- out[curr+1]='\0';
- //cout<<out<<endl;
- if(!isContain(l,out))//判断是否包含此种结果,不包含则插入链表
- InsertList(l,out);
- if(i<length-1)
- Backtrack(str,out,length,curr+1,i+1);
- }
- }
- voidmain()
- {
- charstr[]="1223";
- char*out=newchar[strlen(str)+1];
- Backtrack(str,out,strlen(str),0,0);
- Print(l);
- }