题目:
题目大意:
输入一个整数表示输入的测试样例
对于每一个样例输入一串字符,对其中的每一个字符进行全排列并输出
需要注意的是大写字母在相应的小写字母之前。
所以正确的字母顺序是’a’<‘a’<‘b’<‘B’<…<‘z’<‘Z’。
代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <set>
#include<cstring>
using namespace std;
bool vis[15];
char res[15];
struct Anagram{
int num;
char ch;
}gram[15];
int len;
bool cmp(Anagram a, Anagram b) {
return a.num < b.num; //排序
}
void dfs(int s) {
if (s == len) {
res[len] = '\0';
printf("%s\n", res); //打印结果
return;
}
char c = '.'; //c为标记是否遇见重复字母,例如aabd,则应该直接跳过第二个a
for (int i = 0; i < len; i++) {
if (!vis[i] && c != gram[i].ch) {
vis[i] = true; //标记
c = gram[i].ch;
res[s] = gram[i].ch;
dfs(s + 1);
vis[i] = false; //回溯
}
}
}
int main() {
int n;
char words[15];
while (scanf("%d", &n) != EOF) {
while (n--) {
memset(vis, false, sizeof(vis));
scanf("%s", words);
len = strlen(words);
for (int i = 0; i < len; i++) {
gram[i].ch = words[i];
if (words[i] >= 'a' && words[i] <= 'z') { //AaBb 0123编号排序
gram[i].num = (words[i] - 'a') * 2 + 1;
}
else if (words[i] >= 'A' && words[i] <= 'Z') {
gram[i].num = (words[i] - 'A') * 2;
}
}
sort(gram, gram + len, cmp); //排序,编号从小到大
dfs(0);
}
}
}
当然这个题目也可以用next_permutation函数进行解答:
#include <algorithm>
#include<iostream>
#include<string.h>
using namespace std;
char a[20];
bool cmp(const char &a,const char &b)
{
if(tolower(a)==tolower(b))
return a<b;
else
return tolower(a)<tolower(b);
}
int main()
{
int n;
int t;
cin>>n;
while(n--)
{
cin>>a;
t=strlen(a);
sort(a,a+t,cmp);
cout<<a<<endl;
while(next_permutation(a,a+t,cmp))
{
cout<<a<<endl;
}
}
return 0;
}
当然:
这相当与是取巧了。
这里用到了next_permutation函数
next_permutation函数具体用法
以及tolower函数(把字母字符转换成小写,非字母字符不做出处理)
tolower函数具体用法