Bài này tuy cơ bản, nhưng mới học cũng khá vất vả đó, đọc kĩ cố gắng hiểu mà chắc đọc code không cũng khó, bạn tìm sách giải thuật của Lê Minh Hoàng, có giải thích bài này khá cặn kẽ, đó là cuốn mình yêu thích nhất T_T nhưng phải biết Pascal.
PHP Code:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
static int size;
std::cout << "Enter size of array : " << std::endl;
std::cin >> size;
std::vector<int> A(size, 0);
int position,
temp,
a,b;
for(int x = 0; x < size; x++)
{
A[x] = x + 1;
}
for(int x = 0; x < size; x++)
{
std::cout << A[x] << std::setw(5);
}
cout << "\n\n";
cout << "-------Permutation Algorithm--------------" << "\n\n";
/* PERMUATION ALGORITHM */
do
{
for(position = 0; position < size; position++)
{
std::cout << A[position] << "," << setw(3);
}
std::cout << std::endl << std::endl;
position = size - 2;
/*Kiểm tra coi có phải là cấu hình cuối cùng chưa*/
while(position >= 0 && (A[position] > A[position+1]))
{
position--;
}
if(position >= 0)
{
temp = size - 1 ;
while(A[temp] < A[position])
temp--;
swap (A[temp], A[position]);
a = position + 1;
b = size - 1;
/*Chỗ này là kĩ thuật ánh gương*/
while(a < b)
{
swap(A[a], A[b]);
a++;
b--;
}
}
}
while(position >= 0);
return 0;
}