#include <iostream>
using namespace std;
#define NUM_COUNT 6
int count; // 全排列个数
int num[NUM_COUNT]; // 给定全排列数据
void swap(int & a, int & b)
{
if (a != b) {
a ^= b;
b ^= a;
a ^= b;
}
}
void init()
{
count = 0;
for (int i = 0; i < NUM_COUNT; i++) {
num[i] = i + 1;
}
}
void permute(int i)
{
if (i < NUM_COUNT) {
for (int j = i; j < NUM_COUNT; j++) {
swap(num[i], num[j]);
permute(i + 1);
swap(num[i], num[j]);
}
}
else {
++count;
cout << " { ";
for (int i = 0; i < NUM_COUNT; i++) {
cout << num[i] << " ";
}
cout << "}" << endl;
}
}
void permute()
{
init();
permute(0);
}
int main()
{
permute();
cout << "====== count = " << count << endl;
return 0;
}
起初在实现permute的swap时:
我没有做if (a !=b)这个判断, 一般情况我们也没有必要这样做, 但是如果a和b是同一个元素时, a ^= b之后a变成了0, 因为a和b是同一个变量, 所以b也成了0, 之后再b ^= a; a ^= b; 最终出来时a和b所代表的元素变成了0
增加下利用STL提供的next_permutation/prev_permutation的实现:
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
void show(int num[], int length)
{
for (int i = 0; i < length; ++i) {
cout << num[i] << " ";
}
cout << endl;
}
int main()
{
{
cout << "-- test1 --" << endl;
int count = 0;
int num[] = {1, 2, 3, 4, 5, 6};
int length = sizeof(num) / sizeof(num[0]);
show(num, length);
++count;
while (next_permutation(num, num + length, less<int>())) {
show(num, length);
++count;
}
cout << "--- " << count << " ---" << endl;
}
getchar();
{
cout << "-- test2 --" << endl;
int count = 0;
int num[] = {6, 5, 4, 3, 2, 1};
int length = sizeof(num) / sizeof(num[0]);
show(num, length);
++count;
while (next_permutation(num, num + length, greater<int>())) {
show(num, length);
++count;
}
cout << "--- " << count << " ---" << endl;
}
return 0;
}