题目
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
解题思路
这是经典的DFS题目
大致思想是,先确定第i个字符(从i到最后完成遍历枚举),然后对i+1~N-1个字符递归使用全排列(缩小范围)。
源代码
import java.util.ArrayList;
import java.util.Collections;
public class Permutation {
public static void main(String[] args) {
System.out.println(Permutation("abc"));
}
public static ArrayList<String> Permutation(String str) {
ArrayList<String> res = new ArrayList<>();
if (str == null || str.length() == 0) {
return res;
}
char[] chars = str.toCharArray();
findPermutation(res, chars, 0);
Collections.sort(res);
return res;
}
//对chs[i~length-1]范围内的字符数组完成全排列,并将结果存入res中
private static void findPermutation(ArrayList<String> res, char[] chars, int i) {
if (i == chars.length) {
res.add(new String(chars));
return;
}
//从[i~length-1]枚举确定i位置的字符
for (int j = i; j < chars.length; j++) {
//交换
swap(chars, i, j);
//确定好i的位置,对[i+1~length-1]范围内的字符数组完成全排列
findPermutation(res, chars, i + 1);
//恢复原数组
swap(chars, i, j);
}
}
private static void swap(char[] chars, int i, int j) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}