题目描述
亮亮深吸一口气,小心地将盒子打开,里面是一张地图,地图上除了一些奇怪的字母以外没有任何路线信息,这可让亮亮犯了愁,这些字母代表了什么意思呢? 亮亮绞尽脑汁也想不出什么思路,突然,亮亮眼前一亮,“我可以把这些字母所有的排列方式全部写出来,一定可以找到答案!” 于是,亮亮兴奋的开始寻找字母里的秘密。
输入描述:
每组数据输入只有一行,是一个由不同的大写字母组成的字符串,已知字符串的长度在1到9之间,我们假设对于大写字母有’A’ < ‘B’ < … < ‘Y’ < ‘Z’。
输出描述:
输出这个字符串的所有排列方式,每行一个排列,要求字母序比较小的排列在前面。
输入例子:
WHL
输出例子:
HLW
HWL
LHW
LWH
WHL
WLH
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
ArrayList<String> permutation = Permutation(sc.next());
// permutation.forEach((x) -> {
// System.out.println(x);
// });
for (String x : permutation) {
System.out.println(x);
}
}
sc.close();
}
public static ArrayList<String> Permutation(String str) {
ArrayList<String> al = new ArrayList<String>();
if (str == null || str.length() == 0 || str.length() > 9)
return al;
ArrayList<String> sal = str2al(str);
ArrayList<ArrayList<String>> Perm = calPerm(sal);
for (int i = 0; i < Perm.size(); i++) {
al.add(al2str(Perm.get(i)));
}
HashSet<String> hs = new HashSet<String>(al);
ArrayList<String> res = new ArrayList<String>(hs);
Collections.sort(res);
return res;
}
public static void calPermRecursion(ArrayList<ArrayList<String>> tal, ArrayList<String> sal, int n) {
if (n == sal.size()) {
tal.add(new ArrayList<String>(sal));
} else {
for (int i = n; i < sal.size(); i++) {
Collections.swap(sal, i, n);
calPermRecursion(tal, sal, n + 1);
Collections.swap(sal, i, n);
}
}
}
public static ArrayList<ArrayList<String>> calPerm(ArrayList<String> sal) {
ArrayList<ArrayList<String>> tal = new ArrayList<ArrayList<String>>();
calPermRecursion(tal, sal, 0);
return tal;
}
public static ArrayList<String> str2al(String s) {
ArrayList<String> al = new ArrayList<String>();
for (int i = 0; i < s.length(); i++) {
al.add(String.valueOf(s.charAt(i)));
}
return al;
}
public static String al2str(ArrayList<String> al) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < al.size(); i++) {
sb.append(al.get(i));
}
return sb.toString();
}
}