求几个数的全排列:
#include <iostream>
#include <string>
using namespace std;
int map[100]; //假设排列数的个数最多为100
int n;//实际个数
int q;//多少种不同的数
int icount[100];//存放每种不同的数的个数。数组大小由q决定
int itable[100];//存放一种排序
int num; //统计有多少种排列
void reslove(int pos)
{
if (pos == n)//如果pos==n,说明已排列好一种,输出
{
num++; //排列数+1;
for (int i = 0; i < n; i++)
cout << map[itable[i]] << "\t";
cout << endl;
return;
}
else
{
for (int i = 0; i < q; i++) //从q种数中选择一个放入此位置
{
if (icount[i] == 0)continue; //如果此i种类的数没有了,则继续for循环
itable[pos] = i;
icount[i]--;
reslove(pos + 1); //递归向前
icount[i]++; //递归返回后,此位置将换其它类型的数,故i类型的数恢复+1,用来给后面的位置选取
}
}
}
int main()
{
while (cin >> n && n)
{
/*
全局变量初始化
*/
q = 0;
num = 0;
memset(map, 0, sizeof(map));
memset(icount, 0, sizeof(icount));
memset(itable, 0, sizeof(itable));
int x;
/*
处理输入,重复种类的数不存放map
*/
for (int i = 0; i < n; i++)
{
cin >> x;
int j;
for (j = 0; j < q; j++)//跟之前存放的q种数比较
{
if (map[j] == x)//如果相等,则只是将这种数的个数 + 1,并不存放在map中
{
icount[j]++;
break;
}
}
if (j == q) // 如果此数与其他数各不相同,则将其存放map中
{
map[j] = x;
icount[j]++; //将此种数的个数+1
q++; //数的种类+1
}
}
/*
深搜+回溯
*/
reslove(0);
cout <<"排列总数: "<< num << endl;
}
system("pause");
return 0;
}