参考了网上大神的判重方法, 还有用c++函数next_permutation(a,a+n), 字符数组a是数组开始全排列的状态,随后字典序排列输出,n为长度。如果需要输出全部的排列,需要对字符数组a排序。
全排列的实质是将前面的数与后面不和已经使用过并且和当前相同的字符交换。这句话交换是全排列,但是出现aab这样的需要去重,就需要刚刚说过的后面这句绕口的话。
计蒜客 全排列
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N=1e3;
char str[N], buf[N];//buffer
int vis[N], total, len;
void arrange(int num) {
if (num == len){
printf("%s\n", buf);
total++;
return;
}
for (int i = 0; i < len; ++i) {
if (!vis[i]) {
int j;
for (j = i + 1; j < len; ++j) {
if (vis[j]&&str[j]==str[i]) {
break;
}
}
if (j == len) {
vis[i] = 1;
buf[num] = str[i];
arrange(num + 1);
vis[i] = 0;
}
}
}
}
int main() {
while (~scanf("%s",str)) {
len = strlen(str);
sort(str, str + len);
total = 0;
buf[len] = '\0';
arrange(0);
printf("Total %d\n", total);
}
return 0;
}
51nod 全排列
#include<iostream>
#include<cstdio>
#include <cstring>
#include <algorithm>
#define LL long long
using namespace std;
const int N = 50;
bool vis[N];
char str[N], ans[N];
int len;
void dfs(int cur)
{
if(cur==len)
{
printf("%s\n", ans);
return ;
}
for(int i = 0; i<len;i++)
{
if(!vis[i])
{
vis[i] = 1;
ans[cur] = str[i];
dfs(cur+1);
vis[i]=0;
while(i<len&&str[i]==str[i+1])i++;
}
}
}
int main()
{
while(~scanf("%s", str))
{
len = strlen(str);
sort(str, str+len);
dfs(0);
}
return 0;
}