7 POJ 1256 Anagram
來源:程序員人生 發布時間:2015-05-08 08:12:48 閱讀次數:3450次
給1個字符串包括大小寫字符,規定'A'<'a'<'B'<'b'<...<'Z'<'z',求該字符串的全排列。
用裸的dfs+map判重 寫了1遍超時了,那種機靈的dfs方法沒有怎樣看懂。。
最開始用的set+next_permutation,太年輕,也超時了。。。
應用1個next_permutation()函數便可,<algorithm>頭文件
注意要先將字符串sort1遍,然后next_permutation()也要把比較函數cmp傳進去,原來都不知道可以3個參數的。。
#include<cstdio>
#include<set>
#include<cstring>
#include<algorithm>
#include<string>
#include<iostream>
using namespace std;
char s[20];
bool cmp(char a,char b)
{
if(a>='a'&&a<='z'&&b>='a'&&b<='z') return a<b;
if(a>='A'&&a<='Z'&&b>='A'&&b<='Z') return a<b;
if(abs(a-b)==32) return a<b;
if(a>='A'&&a<='Z') a+=32;
if(b>='A'&&b<='Z') b+=32;
return a<b;
}
int main()
{
int T,len;
scanf("%d",&T);
while(T--)
{
scanf("%s",s);
len=strlen(s);
sort(s,s+len,cmp);
do
{
puts(s);
}while(next_permutation(s,s+len,cmp));
}
return 0;
}
用裸的dfs+map判重 寫了1遍超時了,那種機靈的dfs方法沒有怎樣看懂。。
最開始用的set+next_permutation,太年輕,也超時了。。。
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈