基本思想:以四个数为例,先把第一个位置的数固定,递归地求后三个数的全排列,在求后三位的全排列时,把这三位中的第一位(整个数列中的第二位)固定,以此类推。当只剩最后一个数要被固定时就可以输出了。比如0123,先是输出0123(全固定),然后2取消固定,和3进行交换,交换后一组全排列输出完毕要交换回来。0123和0132输出之后,1取消固定,1和2进行交换,固定2,接下去一系列和之前一样。再是1.3交换。
代码:
#include <iostream>
#include <string>
using namespace std;
void swap(string &a, string &b)
{
string temp = a;
a = b;
b = temp;
}
void perm(char list[], int k, int m)
{
if (k == m)
{//只剩下一个元素
for (int i = 0; i <= m; i++)
cout << list[i];
cout << endl;
}
else//还有多个元素待排列,递归产生排列
for (int i = k; i <= m; i++)
{
//从固定的数开始依次进行交换
swap(list[k], list[i]);
perm(list, k + 1, m);
//把之前交换的顺序换回来
swap(list[k], list[i]);
}
}
int main()
{
string a;
char list[10000];
int n;
cout << "请输入需要全排列组合的元素个数:" << endl;
cin >> n;
cout << "请输入请输入需要全排列的组合:" << endl;
cin >> a;
strncpy_s(list, a.c_str(), n);//或strcpy_s(list, a.c_str());
perm(list, 0, n-1);
system("pause");
}