生成字符串的全排列,可以用回溯法实现,具体代码如下:
/* 回溯法生成字符串的全排列 */
#include "stdafx.h"
void perm(char a[], int t);
void swap(char a[], int i, int j); /* 交换数组a中下标为i和j的元素的位置 */
int _tmain(int argc, _TCHAR* argv[])
{
char a[] = "ABC";
perm(a, 0);
system("pause");
return 0;
}
void swap(char a[], int i, int j)
{
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
void perm(char a[], int t)
{
if (t == strlen(a)) { /* 已搜索至叶结点 */
for (int i = 0; i < strlen(a); i ++) printf("%c ", a[i]);
printf("\n");
} else
for (int i = t; i < strlen(a); i++) {
swap(a, t, i);
perm(a, t + 1); /* 搜索子结点 */
swap(a, t, i); /* 恢复初始序列以回溯 */
}
}