字符串的全排列和组合

来源:互联网 发布:优绘下载 mac版 编辑:程序博客网 时间:2024/05/21 08:42

字符重复也可以

#include <iostream>
#include <vector>
using namespace std;


//字符串排列
void Permutation(char * pstr,char * begin){
if(*begin =='\0')
{
cout<<pstr<<endl;
}
else{
for(char *pCh=begin;*pCh!='\0';++pCh)
{
char temp = *pCh;  
            *pCh = *begin;  
            *begin = temp; 

Permutation(pstr,begin+1);
//swap(*pCh,*begin);
temp = *pCh;  
            *pCh = *begin;  
            *begin = temp;
}
//cout<<endl;
}
}
bool IsSwap(char * begin,char * end)
{
char *a;
for(a=begin;a<end;a++)
{
if(*a==*end)
{
return false;
}
}
return true;
}
void NoRepeat(char * pstr,char * begin)
{
if(*begin =='\0')
{
cout<<pstr<<endl;
}
else{
for(char *pCh=begin;*pCh!='\0';++pCh)
{
if(IsSwap(begin,pCh))
{
swap(*pCh,*begin);
NoRepeat(pstr,begin+1);
swap(*pCh,*begin);
}
}
}
}
void sortChar(char * pstr)
{
if(pstr==NULL)
{
return;
}
//Permutation(pstr,pstr);
NoRepeat(pstr,pstr);
}


void combination_m(char *pstr,char *begin,int m,vector<char> &result)//排列组合
{
if(pstr==NULL||(*pstr=='\0'&&m!=0))
{
return;
}
if(m==0)
{
for(int i=0;i<result.size();i++)
cout << result[i];  
cout<<endl;
return;
}
bool NoRepeat=true;
for(char *pCh=begin;pCh<pstr;pCh++)
{
if(*pCh==*pstr)
{
NoRepeat=false;
}
}
//选中第一个字符
if(NoRepeat)
{
result.push_back(*pstr);
combination_m(pstr+1,begin,m-1,result);
result.pop_back();
}


//没选第一个字符
combination_m(pstr+1,begin,m,result);


}
void combination(char *pstr)
{
if(pstr==NULL||*pstr=='\0')
{
return;
}
int n=strlen(pstr);
char *begin=pstr;
for(int m=1;m<=n;m++)//c(n,m)从长度n的序列选出长为m的子序列
{
vector<char> result;  
combination_m(pstr,begin,m,result);
}
}
void main(){
//char ss[]="abc";
char *s="abba";
combination(s);
//sortChar(s);
}


0 0
原创粉丝点击