现在的位置: 首页 > 综合 > 正文

对集合{1, 2, 3, …, n}中的数进行全排列,可以得到 n!个不同的排列方式

2013年12月07日 ⁄ 综合 ⁄ 共 483字 ⁄ 字号 评论关闭

题目如下:

. 对集合{1, 2, 3, …, n}中的数进行全排列,可以得到 n!个不同的排列方式。现在我们用字母序把它们列出来,并一一标上序号,如当 n=3 时:
0.123
1.132
2.213
3.231
4.312
5.321
现在,请书写一个函数 void print (int n, int k), (函数原型是用 C语言写的,你可以用你熟悉的语言)在已知 n和序号 k 的情况下,输出对应的排列,并简要阐述思路


想到的是stl中的next_permutation函数,代码如下:

#include<iostream>
#include<algorithm>
using namespace std;

void print(int n, int k){
	//生成1..n的序列并初始化
	char *ch = new char[n+1];//最后一个为结束符
	for(int i=0;i<n;++i)
		ch[i]=i+'1';
	ch[n]='\0';

	
	while(k-->0){
		next_permutation(ch,ch+n);
	}
	cout << ch << endl;

	delete []ch;
}
void main(){
	print(3,5);
}


抱歉!评论已关闭.