全排列程序
算法:递归出口:集合中只有一个元素时,即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综述