输入一个字符串,打印出该字符串中字符的所有排序,例如输入字符串abc,则打印出字符串a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab、cba
//解法一:经典的解法
#include<iostream>
#include<string.h>
using namespace std;void PermutationNumber(char *pstr);
void Permutation(char *pstr , char *pbegin);void PermutationNumber(char *pstr)
{
if(pstr == NULL)
{
return ;
}
Permutation(pstr , pstr);
}void Permutation(char *pstr , char *pbegin)
{
if(*pbegin == '\0')
{
printf(" %s \n",pstr);
}
else
{
for(char * p = pbegin; *p!= '\0';++p)
{
char tmp = *p;
*p = *pbegin;
*pbegin=tmp;
Permutation(pstr , pbegin+1);
tmp = *p;
*p = *pbegin;
*pbegin = tmp;
}
}
}int main()
{
char arr[] = "abcd";
PermutationNumber(arr);
return 0;
}
//解法二:递归
void Perm(char *ar,int k,int m)
{
if(k == m)
{
for(int i = 0;i<=m;++i)
{
cout<<ar[i]<<" ";
}
cout<<endl;
}
for(int j = k ;j <=m;++j)
{
swap(ar[k],ar[j]);
Perm(ar,k+1,m);
swap(ar[k],ar[j]);
}
}
int main()
{
const int n = 3;
char ar[n]={'a','b','c'};
Perm(ar,0,n-1);return 0;
}
//子集问题,输入1,2,3,打印123、12、13、1、23、2、3、 、
void fun(int *ar,int *br,int i,int n)
{if(i == n)
{
for(int j = 0;j<n;++j)
{
if(br[j])
{
cout<<ar[j]<<" ";
}
}
cout<<endl;
}
else
{
br[i] = 1;
fun(ar,br,i+1,n);
br[i] = 0;
fun(ar,br,i+1,n);
}
}int main()
{
int ar[]={1,2,3};
int br[]={0,0,0};
int n = sizeof(ar)/sizeof(ar[0]);
fun(ar,br,0,n);return 0;
}