全排列程序
算法:遞歸出口:集合中隻有一個元素時,即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;
}
最後更新:2017-04-02 18:14:51
上一篇:
Oracle操作報錯:record is locked by another user
下一篇:
android中Intent的一些用法和總結
Xml+Xslt測試工具
關於雲存儲需要弄清的五大問題
Spring-Bean的銷毀使用destroy-method()方法無效解決方案(容器!附源碼)
S是最有安全感的形狀
Java並發——線程間協作(wait、notify、sleep、yield、join)
ELK之ES-Logstash-Kibana互聯
Android開發20——單個監聽器監聽多個按鈕點擊事件
ASP.NET Core的配置(4):多樣性的配置來源[下篇]
Vmware、Virtuozoo、Virtual Server 、Xen四款虛擬機的性能比較
java.util.concurrent解析——AbstractQueuedSynchronizer綜述