原題:
You are to write a program that has to generate all possible words from a given set of letters.
Example: Given the word “abc”, your program should - by exploring all different combination of the three letters - output the words “abc”, “acb”, “bac”, “bca”, “cab” and “cba”.
In the word taken from the input file, some letters may appear more than once. For a given word, your program should not produce the same word more than once, and the words should be output in alphabetically ascending order.
Input
The input file consists of several words. The first line contains a number giving the number of words to follow. Each following line contains one word. A word consists of uppercase or lowercase letters from A to Z. Uppercase and lowercase letters are to be considered different.
Output
For each word in the input file, the output file should contain all different words that can be generated with the letters of the given word. The words generated from the same input word should be output in alphabetically ascending order. An upper case letter goes before the corresponding lower case letter.
Sample Input
3
aAb
abc
acba
Sample Output
Aab
Aba
aAb
abA
bAa
baA
abc
acb
bac
bca
cab
cba
aabc
aacb
abac
abca
acab
acba
baac
baca
bcaa
caab
caba
cbaa
中文:
給你一個字串,由大小寫字母組成,有重複的元素,現在讓你輸出所有的字串排列。按照字串大小AaBb…..Zz的順序給出。
#include<bits/stdc++.h>using namespace std;typedef long long ll;int mark[140];vector<string> vs;int cmp(const char &c1,const char &c2){ return mark[c1]<mark[c2];}void permutation(int n,char *P,char *A,int cur){ if(cur==n) { string tmp; tmp.assign(A,n); vs.push_back(tmp); } 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++; for(int j=0;j<n;j++) if(P[i]==P[j]) c2++; if(c1<c2) { A[cur]=P[i]; permutation(n,P,A,cur+1); } } } }}int main(){ ios::sync_with_stdio(false); memset(mark,0,sizeof(mark)); for(int i='A',j='a',k=0;i<='Z'&&j<='z';i++,j++,k+=2) { mark[i]=k; mark[j]=k+1; } char s[100]; char p[100]; int t; cin>>t; while(t--) { cin>>p; vs.clear(); sort(p,p+strlen(p),cmp); permutation(strlen(p),p,s,0); for(int i=0;i<vs.size();i++) cout<<vs[i]<<endl; } return 0;}
解答:
先自己寫一個排序的函數,把給定的字串按照規則排個序,使用紫書上可重集排列模板即可。