先从理论上来分析递归解决全排列的可行性
n个元素将产生n!的排列
令E = {1,4……7,9}的n个元素的集合,Ei为E移除i个元素后的集合,perm(x)为x元素的全排列
eiperm(x)表示在perm的排列的每个排列前面加上ei
从n = 1开始,显然,当n只有一个元素时,排列方式只有一种
当n > 1时,perm(E) = e1.perm(E1)+e2.perm(E2)……en.perm(En)
for example: a.perm({b , c}) = ab.perm({c}) + ac.perm({b});
代码实现perm的逻辑
template<class T>
void Perm(T list[], int k, int m)
{
//若k == m,则输出排列
if(k == m)
{
for(int i = 0; i < m; i ++)
{
cout << list[i] << endl;
}
}
else
{
for(i = k; i < m; i ++)
{
Swap(list[i], list[k]);
Perm(a, k, m);
Swap(list[k], list[i]);
}
}
}
#include <iostream>
using namespace std;
template<class T>
inline void Swap(T &a, T &b)
{
T temp = a;
a = b;
b = temp;
}
template <class T>
void Perm(T list[], int k, int m)
{
int i;
//输出排列方式
if(k == m)
{
for(i = 0; i<= m; i ++)
{
cout << list[i];
}
cout << endl;
}
else
{
//产生排列方式
for(i = k; i <= m; i ++)
{
Swap(list[k], list[i]);
Perm(list, k + 1, m);
Swap(list[k], list[i]);
}
}
}
int main(int argc, char* argv[])
{
int a[] = {1, 2, 3, 4, 5};
Perm<int>(a, 0, 4);
return 0;
}