枚举排列
根据字典序,依次输出全排列,整理一下,有两种方法:一种递归,一种利用C++中的STL
一:生成可重集的排列
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int p[20];
int cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
void print_permutation(int n, int *a, int cur)
{
if (cur == n)
{
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
else
{
for (int i = 0; i < n; i++)
{
if (!i || p[i] != p[i - 1])//防止重复的数多次输出,需要先排序
{
int c1 = 0, c2 = 0;//为了顺利输出存在相同的情况
for (int j = 0; j < cur; j++)
if (a[j] == p[i])
c1++; //寻找现排列中与原排列相同的个数c1
for (int j = 0; j < n; j++)
if (p[j] == p[i])
c2++; //原排列中自身重复的个数c2
if (c1 < c2) //c1<c2即可递归
{
a[cur] = p[i];
print_permutation(n, a, cur + 1);
}
}
}
}
}
int main()
{
int a[20];
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", &p[i]);
qsort(p, n, sizeof(p[0]), cmp);
print_permutation(n, a, 0);
return 0;
}
二:下一个排列
#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
int n, p[10];
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", &p[i]);
sort(p, p + n);
do {
for (int i = 0; i < n; i++)
printf("%d ", p[i]);
printf("\n");
} while (next_permutation(p, p + n));//直接while不会输出自身(输入的那个序列)
return 0;
}
15236235 | Seasonal | 1146 | Accepted | 164K | 0MS | C++ | 256B | 2016-03-06 16:45:09 |
#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
char a[500];
while (scanf("%s", a) && a[0] != '#')
{
int n = strlen(a);
if (next_permutation(a, a + n))//如果存在下一个排列返回true,否则返回false
printf("%s\n", a);
else
printf("No Successor\n");
}
return 0;
}