輸出全排列的兩種方式
在暴力求解問題中,我們經常會枚舉全排列,在此我列了列出了兩種枚舉全排列的兩種方式。已輸出1-5的全排列爲例。
方式1:用回溯算法(深度優先遍歷DFS)
/**
* Author: ACb0y
* FileName: Test.cpp
* Create Time: 2011年9月22日23:00:51
* Version: 1.0
*/
#include <iostream>
using namespace std;
const int MAX = 10;
class Permutation
{
public:
int n;
int vis[MAX];
int data[MAX];
int cnt;
Permutation(int n);
void printAllPermutation();
private:
void printData();
void dfs(int pos);
};
Permutation::Permutation(int n)
{
this->n = n;
cnt = 0;
}
void Permutation::printData()
{
for (int i = 0; i < n; ++i)
{
cout << data[i] << " ";
}
cout << endl;
}
void Permutation::dfs(int pos)
{
int i, j;
if (pos == n)
{
printData();
++cnt;
}
else
{
for (i = 1; i <= n; ++i)
{
if (!vis[i])
{
data[pos] = i;
vis[i] = 1;
dfs(pos + 1);
vis[i] = 0;
}
}
}
}
void Permutation::printAllPermutation()
{
memset(vis, 0, sizeof(vis));
dfs(0);
cout << "count = " << cnt << endl;
}
int main()
{
Permutation a(5);
a.printAllPermutation();
return 0;
}
方式2:STL的next_permutation函數
/**
* Author: ACb0y
* FileName: Test.cpp
* Create Time: 2011年9月22日23:00:51
* Version: 1.0
*/
#include <iostream>
using namespace std;
int main()
{
int i, j;
int data[5];
for (i = 0; i < 5; ++i)
{
data[i] = i + 1;
}
do
{
for (j = 0; j < 5; ++j)
{
cout << data[j] << " ";
}
cout << endl;
}while (next_permutation(data, data + 5));
return 0;
}