题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则按字典序打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
思路:dfs
public class Permutation {
public static void main(String[] args) {
String s = "abc";
List<List<String>> res = Lists.newArrayList();
permutation(res, s.toCharArray(), 0);
System.out.println(res);//[[abc], [acb], [bac], [bca], [cba], [cab]]
List<String> list = res.stream().flatMap(Collection::stream).collect(Collectors.toList());
System.out.println(list);//[abc, acb, bac, bca, cba, cab]
}
public static void permutation(List<List<String>> result, char[] chars, int index) {
// 1.终止条件
// 2.大容器添加小容器
if (index == chars.length) {
String s = String.valueOf(chars);
String[] split = s.replaceAll(" ", "").split(",");
List<String> path = Arrays.stream(split).filter(str -> !Objects.equals(s, "")).collect(Collectors.toList());
result.add(path);
return;
}
// 3.循环
for (int i = index; i < chars.length; i++) {
// 3.1过滤|去重
// 3.2优化减支
// 3.3小容器添加元素(这里使用chars数组本身作为我们的小容器)
swap(chars, i, index);
// 3.4递归(横向是bfs,即循环即j++、纵向是dfs,即递归即i++)
permutation(result, chars, index + 1);
// 3.5回溯(原本是删除小容器的最后一个元素,这里是将小容器即chars数组还原,因为我们使用它作为小容器进行变化然后添加至大容器,所以作为数组本身还需要回溯回来)
swap(chars, i, index);
}
}
private static void swap(char[] chars, int i, int index) {
char temp = chars[i];
chars[i] = chars[index];
chars[index] = temp;
}
}