/**
* Created by zzh on 2018/12/30.
*/
public class Test {
public static List<List<Character>> allSort(List<Character> chars){
if(chars.size() == 1) {
List<List<Character>> list = new ArrayList<>();
list.add(chars);
return list;
}
List<List<Character>> list = new ArrayList<>();
List<Character> useList = new ArrayList<>();
List<Character> others = new ArrayList<>(chars);
for (Character ch : chars) {
if (useList.contains(ch)) {
// 如果已经使用过重复元素的一个,就不再使用
continue;
} else {
// 记录使用过的元素
useList.add(ch);
}
// 移除当前的元素,得到剩下的元素
others.remove(ch);
// 拿剩下的数据进行全排列
List<List<Character>> othersAllSort = allSort(others);
// 当前的元素和剩下的元素的全排列,拼接下就可以了
for (List<Character> othersAllSortItem : othersAllSort) {
List<Character> dest = new ArrayList<>(othersAllSortItem);
dest.add(0, ch);
list.add(dest);
}
// 恢复元素列表,便于下次循环复用
others.add(ch);
}
return list;
}
public static void main(String[] args){
List<Character> src = Arrays.asList('a', 'a', 'b');
List<List<Character>> allSortList = allSort(src);
allSortList.forEach(Test::print);
}
private static void print(List<Character> chars){
for (Character ch : chars) {
System.out.print(ch + " ");
}
System.out.println();
}
}
a a b
a b a
b a a