算法:遞歸出口:集合中隻有一個元素時,即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]);
inline void swap(char& c1, char& c2)
char tmp = c1;
c1 = c2;
c2 = tmp;