求第N个排列数

设序列为N个M位数的基本数字组成的排列数(N<=M)

假设序列是有序的,求第n个排列数(以0开始索引,0<=n<N!)

 

GetNofP
void GetNofP(char const * const in,char* out,int const size,unsigned long long N)
//in必须为递增的序列,size为in的大小
//out为结果序列,out的大小必须大于size
//0<=N<size!

{
strcpy(out,in);
vector<unsigned long long > info(size);
int pos = size -1;
info[pos] = 1;
int i =1;
--pos;
while(pos>=0)
{
info[pos] = info[pos+1]*i;
++i;
--pos;
}
for(int i = 0;N!=0&&i<size;++i)
{
unsigned long cur =(unsigned long) (N/info[i]);
if(cur==0)
continue;
int newPos = i+cur;
int curVal =out[i];
out[i] = out[newPos];
--newPos;
while(newPos>i)
{
out[newPos+1]=out[newPos];
--newPos;
}
out[i+1] = curVal;
N = N%info[i];
}
}

测试代码

测试代码
int main(int argc, char* argv[])
{
char arr[] = "1234";
char out[sizeof(arr)];
unsigned long long sum =0;
int size =sizeof(arr)/sizeof(arr[0]) -1;
sum=1;
for(int i=1;i<=size;++i)
{
sum*=i;
}
int beg = GetTickCount();
for(unsigned long long i=0;i<sum;++i)
{
GetNofP(arr,out,size,i);
cout<<out<<endl;
}
int end = GetTickCount();
cout<<(end - beg)<<endl;
cout<<sum<<endl;

return 0;
}
输出结果
1234
1243
1324
1342
1423
1432
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241
3412
3421
4123
4132
4213
4231
4312
4321
0
24
请按任意键继续. . .




posted on 2011-10-13 17:24  SammyLan  阅读(359)  评论(0编辑  收藏  举报

导航