問題簡述:
輸出一串字符的全排列,順序不同於一般的字母序,而是 A<a<B<b......<Z<z。所以應該重寫一個比較函數。
原題鏈接:http://poj.org/problem?id=1256
解題思路:
兩種方法:
方法一:簡單的深搜 DFS 搜索所有的可能,但是要注意幾個連續相同的字符算作一種情況。
方法二:使用 STL 的 next_permutation 函數可以很方便的生成全排列。
關於 next_permutation 函數,可以參考:姜南(Slyar)的文章(點擊直接跳轉) 感謝原作者!
DFS源代碼:
/*
OJ: POJ
ID: 3013216109
TASK: 1256.Anagram
LANG: C++
NOTE: DFS
*/
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
int n;
char str[13],ans[13];
int visited[13];
bool cmp(char a,char b) {
if(tolower(a)==tolower(b))
return a<b;
else
return tolower(a)<tolower(b);
}
void dfs(int t) {
if(t==strlen(str)) {
for(int i=0;i<t;i++)
printf("%c",ans[i]);
printf("\n");
return;
}
for(int i=0;i<strlen(str);i++) {
if(!visited[i]) {
ans[t]=str[i];
visited[i]=1;
dfs(t+1);
visited[i]=0;
while(i+1<strlen(str)&&str[i]==str[i+1]) i++;
}
}
}
int main()
{
scanf("%d",&n);
getchar();
while(n--) {
memset(visited,0,sizeof(visited));
gets(str);
sort(str,str+strlen(str),cmp);
dfs(0);
}
return 0;
}
STL源代碼:
/*
OJ: POJ
ID: 3013216109
TASK: 1256.Anagram
LANG: C++
NOTE: NEXT_PERMUTATION
*/
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
int n;
char str[13];
bool cmp(char a,char b) {
if(tolower(a)==tolower(b))
return a<b;
else
return tolower(a)<tolower(b);
}
int main()
{
scanf("%d",&n);
getchar();
while(n--) {
gets(str);
sort(str,str+strlen(str),cmp);
do {
puts(str);
} while(next_permutation(str,str+strlen(str),cmp));
}
return 0;
}