优点:该方法易于理解,但无法移除重复的排列,如:s="ABA",会生成两个“AAB”。
方法2:利用交换的思想,具体见实例,但该方法不如方法1容易理解。
//方法2:利用交换的思想,具体见实例,但该方法不如方法1容易理解。
//
//?
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
void swap(char* x, char* y)
{
if(x==y)
return;
char tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
/* Function to print permutations of string
This function takes three parameters:
1. String
2. Starting index of the string
3. Ending index of the string. */
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
{
for (j = i; j <= n; j++)
{
if(a[i] == a[j] && j != i) //为避免生成重复排列,当不同位置的字符相同时不再交换
continue;
swap((a+i), (a+j));//a[i]<->a[j]
permute(a, i+1, n);
swap((a+i), (a+j)); //backtrack//a[i]<->a[j]
}
}
}
void permute_my(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
{
for (j = i; j <= n; j++)
{
if(a[i] == a[j] && j != i) //为避免生成重复排列,当不同位置的字符相同时不再交换
continue;
//swap((a+i), (a+j));//a[i]<->a[j]
char buff[256];
strcpy(buff,a);
swap(&buff[i],&buff[j]);//buff[i]<->buff[j]
permute_my(buff, i+1, n);
//swap((a+i), (a+j)); //backtrack//a[i]<->a[j]
}
}
}
int main()
{
//method2
cout << "method2" << endl;
char a[] = "ABA";
permute(a,0,strlen(a)-1);
///////
printf("==========\n");
char b[] = "ABA";
permute_my(b,0,strlen(b)-1);
return 0;
}
两种方法的生成结果:
method1
ABA
AAB
BAA
BAA
AAB
ABA
method2
ABA
AAB
BAA
请按任意键继续. . .
|