现在有一道很简单的题目,那就是输出1——n的所有排列数!
比如说,输入n=5;那么要求求出1,2,3,4,5这几个数所有的排列数!
c++中有一个next_permutation函数,它包含在algorithm头文件中,可以方便的求出所有的排列
数,可是你知道它是怎么实现的么?
对那个函数进行了简单的模拟,模拟函数如下:
// next_permutation(begin(),end()+1) 存在返回正数,否则返回0
// prev_permutation(begin(),end()+1)
#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
int n;
int num[50];
scanf ("%d",&n);
for (int i = 1 ; i <= n ; i++)
{
num[i] = i;
}
do
{
for (int i = 1 ; i <= n ; i++)
printf ("%d%c",num[i],i == n ? '\n' : ' ');
}while(next_permutation(num+1,num+1+n));
return 0;
}
#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAX 100
using namespace std;
int main()
{
int length;
char str[MAX];
gets(str);
length = strlen(str);
sort(str, str + length);
puts(str);
while (next_permutation(str, str + length))
{
puts(str);
}
return 0;
}