#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
void swap(char* x, char* y)
{
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) //结果如下:ABC ACB BAC BCA CBA CAB
{
int j;
if (i == n) //当n=2时,每次i等于2时才会打印整个字符串,此时表示已经无法交换,达到最后一个字符了
printf("%s\n", a);
// printf("i:%d n=%d %s\n", i, n, a);
else
{
for (j = i; j <= n; j++)
{
// if (a[i] == a[j] && j != i) //为避免生成重复排列,当不同位置的字符相同时不再交换
// continue;
swap((a + i), (a + j)); //第一次调用函数开始,大递归的含义是第一个字符一次和第二个、第三个.......第N个交换
permute(a, i + 1, n); //大递归之后就是剩下的字符串,再从第一个字符开始一次和第2、3....n交换
swap((a + i), (a + j)); //backtrack 交换完再纠正回来 否则 之前的排序顺序就混乱了结果如下: ABC ACB CAB CBA ABC ACB 可以前面正确结果对比
printf("------------%s\n", a);
}
}
}
int main()
{
//method2
cout << "method2" << endl;
char a[] = "ABC";
// 此处也可以加上排序
permute(a, 0, 2);
return 0;
}