算法:递归出口:集合中只有一个元素时,即exPos == setNum时,打印一个排列。
继续递归条件:当exPos<setNum时,递归地产生前缀set[0:setNum-2],最后回到出口,结束递归。
过程中需要交换元素,把后面的元素依次与第一个元素交换,这样就可以第次只处理后setNum-1个元素,而
依次递归,就可以最终到达exPos==setNum的出口条件。
#include <iostream>
using namespace std;
//list is the whole set.
//exPos is the position to exchange with the first element.
//the numbers of the whole set.
void wholeArrage(char* list, int exPos, int setNum);
inline void Swap(char& c1, char& c2);
int main()
{
char set[] = {'a', 'b','c'};
int setNum = 3;
wholeArrage(set, 0, setNum);
return 0;
}
void wholeArrage(char* list, int exPos, int setNum)
{
static int count = 0;
if (exPos == setNum-1)
{
count ++;
for (int i = 0; i < setNum; i++)
cout << list[i];
cout << " ";
if (count % 10 == 0)
cout << endl;
}
else
{
for (int i = exPos; i < setNum; i++)
{
Swap(list[i], list[exPos]);
wholeArrage(list, exPos+1, setNum);
Swap(list[i], list[exPos]);
}
}
}
{
char tmp = c1;
c1 = c2;
c2 = tmp;
}