#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[10]={1,2,2,3,3,3,4,5,6,7};
int cnt=0;
do{
cnt++;
}while(next_permutation(a,a+10));
printf("%d\n",cnt);//輸出302400
scanf("pause");
}
next_permutation的返回值如下:如果變換后序列是非減序的則返回0,否則返回1。
所以如果想用do{...}while(next_permutation(...));的方式生成一個集合的全排列,必須先做sort。
即 便做了sort,從上面的例子我們也可以看出,當集合存在重復(fù)元素時,循環(huán)的次數(shù)并不是10!=3628800,302400是什么呢,恰是10!/ (2!*3!),也就是這個多重集的全排列數(shù)。可見在處理有重復(fù)元素的"集合"時,它是正確的且高效的,只要記住一定要先sort