#include <functional> // std::function
#include <memory> // std::shared_ptr
#include <vector>
#include <iostream>
using namespace std;
// n 取 n 做排列
// 採用逆時旋轉排列法
class Permutation_nPn
{
// 回報結果
function<void(const shared_ptr<vector<unsigned char> > &)> m_Report;
// 放置要排的數字
shared_ptr <vector<unsigned char> > m_Digital_Array;
void v(size_t n)
{
if (n == 0)
m_Report(m_Digital_Array);
else
{
size_t i = n + 1;
while (i--)
{
v(n - 1);
unsigned char tmp = m_Digital_Array->at(n);
for (size_t j = n; j > 0; --j)
m_Digital_Array->at(j) = m_Digital_Array->at(j - 1);
m_Digital_Array->at(0) = tmp;
}
}
}
public:
Permutation_nPn(
const function<void(const shared_ptr<vector<unsigned char> > &)>
&Receive
)
:m_Report(Receive)
{}
void nPn(size_t n)
{
m_Digital_Array = shared_ptr<vector<unsigned char> >(
new vector<unsigned char>(n));
size_t i = n;
while (i)
{
m_Digital_Array->at(i - 1) = i - 1;
--i;
}
v(n - 1);
}
};
int N = 1;
void Show(const shared_ptr<vector<unsigned char> > &Digital_Array)
{
cout << N << ":\t";
for (size_t i = Digital_Array->size(); i > 0; --i)
cout << (int)Digital_Array->at(i - 1) << ' ';
cout << endl;
++N;
}
int main()
{
Permutation_nPn P(Show);
cout << "4! 排列:" << endl;
N = 1;
P.nPn(4);
return 0;
}