先上代码:
import java.util.*;
public class FullPermutation {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
char[] str = new char[]{'a','b','c','d'};
solution(str,list,0);
System.out.println(list);
System.out.println(list.size());
Set<String> hashSet = new HashSet<String>();
for (String str1 : list) {
if (hashSet.add(str1)) {
System.out.println(str1);
}
}
}
public static void solution(char[] str,List<String> list,int curIndex) {
// 递归终止条件: curIndex = str.length-1
if (curIndex == str.length-1) {
list.add(String.valueOf(str));
} else {
for (int i = curIndex;i < str.length;i++) {
swap(str,curIndex,i);
solution(str,list,1+curIndex);
swap(str,curIndex,i);
}
}
}
public static void swap(char[] str,int i,int j) {
char tmp = str[j];
str[j] = str[i];
str[i] = tmp;
}
}
其实思想不难,分治法,你可以把“abcd”的全排列问题分成“a”+“bcd”,“b”+“acd”,“c”+“abd”和“d”+“abc”四个子问题来处理,这时“bcd”的全排列就是原问题的子问题,采用递归将子问题抽象出来,问题就迎刃而解,在我看来,这个递归有种归并排序的感觉。