c++中的algorithm头文件中内置了一个next_permutation函数,用来求下一个数组的字典序排列,并且会返回一个布尔值,表示是否存在下一个排列。还有一个相应的prev_permutation函数是求前一个排列。
下面的代码先示范了两个函数的用法,然后是输出整形数组num的全排列。当然别的类型的数组也支持,这里不提。六位的数组会输出6!=7200个排列,所以这里就仅仅输出三个做代表。
#include
#include
using namespace std;
int main(int argc, char const *argv[])
{
int num[6] = {3, 2, 4, 1, 6, 5};
next_permutation(num, num + 6);
cout << "The next permutation is: " << endl;
for (int i = 0; i < 6; ++ i)
cout << num[i] << " ";
cout << endl;
prev_permutation(num, num + 6);
cout << "The previous permutation is: " << endl;
for (int i = 0; i < 6; ++i)
cout << num[i] << " ";
cout << endl;
cout << "The full permutation is: " << endl;
sort(num, num + 6);
do
{
for(int i = 0; i < 3; ++ i)
cout << num[i] << " ";
cout << endl;
} while(next_permutation(num, num + 3));
return 0;
}
The next permutation is:
3 2 4 5 1 6
The previous permutation is:
3 2 4 1 6 5
The full permutation is:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
--------------------------------
Process exited with return value 0
Press any key to continue . . .